搭建好shiro的demo后,发现每一次验证权限都要调用自定义realm的doGetAuthorizationInfo方法,在方法里,从数据库读取用户的相关信息,为用户设置roles和Permission权限,如果每次都从数据库查询肯定是不行的,shiro框架默认使用ehcache缓存。配置方法如下
1. 引入shiro-encache包
2. 配置文件中注入bean
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:config/ehcache-shiro.xml" />
</bean>
其中,encache-shiro.xml文件网上也很多,初步学习时不用研究太深,直接复制一个就能用
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="2000" eternal="true"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<cache name="passwordRetryCache" maxElementsInMemory="2000"
eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="0"
overflowToDisk="false">
</cache>
<cache name="authorizationCache" maxElementsInMemory="2000"
eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="0"
overflowToDisk="false">
</cache>
<cache name="authenticationCache" maxElementsInMemory="2000"
eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="0"
overflowToDisk="false">
</cache>
<cache name="shiro-activeSessionCache" maxElementsInMemory="2000"
eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="0"
overflowToDisk="false">
</cache>
</ehcache>
3. shiro的 中注入缓存对象
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myrealm" />
<property name="cacheManager" ref="cacheManager" />
</bean>
完成后,再次测试,发现多次验证权限时,doGetAuthorizationInfo方法只执行一次,说明缓存设置成功。