缓存
每一次给用户授权时,都是通过realm从数据库中查询权限,为了避免频繁的查询数据库,shiro给我们提供了缓存的能力
用户认证通过后:
第一次授权:通过realm从数据库中查询
第二次授权:直接从缓存中查询
引入包
1. shiro-ehcache.jar
2. ehcache-core.jar
配置缓存
创建缓存文件
在src下创建shiro-ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!--diskStore:缓存数据持久化的目录 地址 -->
<diskStore path="F:\develop\ehcache" />
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
配置缓存管理器
<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm" />
<!-- 注入缓存管理器 -->
<property name="cacheManager" ref="cacheManager"/>
</bean>
<!-- 缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
</bean>
清除缓存
一般情况下,用户正常退出和非正常退出(如关闭浏览器)都会自动清空缓存,但是有时候我们需要手动清空缓存。
例如:修改了一个用户的权限,需要手动清空缓存,否则这个用户只要不退出,权限就一直不改变。
手动情况缓存需要在realm中定义一个方法,然后在其他代码中调用它
在reaml中定义:
//清除缓存
public void clearCached() {
PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
super.clearCache(principals);
}
在其他代码中调用:先注入reaml,在执行clearCached方法
@autowire
private UserRealm userRealm;
userRealm.clearCached();