shiro缓存

针对上边授权频繁查询数据库,需要使用shiro缓存。

缓存流程

shiro中提供了对认证信息和授权信息的缓存。
shiro默认是关闭认证信息缓存的,对于授权信息的缓存shiro默认开启的。
主要研究授权信息缓存,因为授权的数据量大。

用户认证通过。
该用户第一次授权:调用realm查询数据库
该用户第二次授权:不调用realm查询数据库,直接从缓存中取出授权信息(权限标识符)。

使用ehcache
添加Ehcache的jar包

<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.3.2</version>
</dependency>

在spring-shiro.xml中配置cacheManager

<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="customRealm"
<!-- 注入缓存管理器 -->
<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>

配置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>

缓存清空

如果用户正常退出,缓存自动清空。

如果用户非正常退出,缓存自动清空。

如果修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。
需要手动进行编程实现:
在权限修改后调用realm的clearCache方法清除缓存。

下边的代码正常开发时要放在service中调用。
在service中,权限修改后调用realm的方法。
在realm中定义clearCached方法:

//清除缓存
public void clearCached() {
PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
super.clearCache(principals);
}

测试清除缓存controller方法:

@Controller
public class ClearShiroCache

//注入realm
@Autowired
private CustomRealm customRealm;

@RequestMapping("/clearShiroCache")
public String clearShiroCache(){

//清除缓存,将来正常开发要在service调用customRealm.clearCached()
customRealm.clearCached();

return "success";
}

}