内存缓存
使用内存缓存比较简单,只需要给securityManager设置一个MemoryConstrainedCacheManager即可。
//1.初始化shiro的安全管理器
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//2.设置用户的权限信息到安全管理器
//Realm realm = new IniRealm("classpath:shiro.ini");
Realm realm = new ShiroRealm();
securityManager.setRealm(realm);
//3. 配置内存缓存管理器
CacheManager cacheManager = new MemoryConstrainedCacheManager();
securityManager.setCacheManager(cacheManager);
//3. 使用SecurityUtils将securityManager设置到运行环境中
SecurityUtils.setSecurityManager(securityManager);
测试:
@Test
public void test04() {
// 模拟从客户端接收到用户登录输入的用户名和密码(明文)
String username = "admin";
String password = "123456";
// 将明文的密码加密成密文
String salt = MD5Util.md5_salt(username + password);
password = MD5Util.md5(password, salt);
// 登录认证
Subject subject = ShiroUtil.login(username, password);
subject.isPermitted("sys:user:create");//第一次调用了doGetAuthorizationInfo方法
subject.isPermitted("sys:user:upadte");//第二次和第三次使用缓存,不调用doGetAuthorizationInfo方法
subject.isPermitted("sys:user:create");
}
Ehcache缓存
引入依赖:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.1</version>
</dependency>
<!-- shiro-ehcache包已经引用过该包,但是为2.x版本,引入新版本覆盖-->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.0</version>
</dependency>
给securityManager设置一个EhCacheManager即可。
CacheManager ehCacheManager = new EhCacheManager();
securityManager.setCacheManager(ehCacheManager);
Ehcache默认配置文件的位置:
<ehcache>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="shiro-activeSessionCache"
maxElementsInMemory="10000"
overflowToDisk="true"
eternal="true"
timeToLiveSeconds="0"
timeToIdleSeconds="0"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="600"/>
<cache name="org.apache.shiro.realm.text.PropertiesRealm-0-accounts"
maxElementsInMemory="1000"
eternal="true"
overflowToDisk="true"/>
</ehcache>
参数说明:
-
eternal: 缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
-
maxElementsInMemory:缓存中允许创建的最大对象数
-
overflowToDisk:内存不足时,是否启用磁盘缓存。
-
timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,两次访问时间的最大时间间隔值,
这只能在元素不是永久驻留 时有效,如果该值是 0 就意味着元素可以停顿无穷长的时间。
-
timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻 留时有效,
如果该值是0就意味着元素可以停顿无穷长的时间。 -
diskPersistent:设定在虚拟机重启时是否进行磁盘存储,默认为false
-
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。
- FIFO,先进先出
- LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
- LRU,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,
而又需要腾出地方来缓存新的元素的时候, 那么现有缓存元素中时间戳离当前时间最远的元素 将被清出缓存。