使用缓存可以避免需要授权信息时频繁的调用数据库查询的问题。
原理很简单,只要在SecurityManager里注入CacheManager即可。
我们可以自己定义CacheManager的实现,可以是ehcache、redis等等。
1.SecurityManager
在securityManager里配置CacheManager
<!--securityManager-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
<property name="cacheManager" ref="cacheManager"/>
</bean>
2.CacheManager
配置自己的CacheManager
a.使用Ehcache
使用ehcache很简单,3个步骤即可:
- 引入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.9</version>
</dependency>
- 缓存配置
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" dynamicConfig="false">
<diskStore path="java.io.tmpdir"/>
<defaultCache name="defaultCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="600"
timeToLiveSeconds="600"
overflowToDisk="false"
maxElementsOnDisk="100000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
name 代表缓存的名字,在spring-shiro里使用的哪一个缓存,就加载哪一个配置
3. 配置CacheManager
<!--cacheManager-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
</bean>
只需要这3步就可以使用ehcache作为shiro的缓存了
b.使用Redis
使用Redis作为shiro的缓存就需要去实现shiro的Cache以及CacheManager即可。
首先需要将Redis整合到项目中,这里不做详细描述,可以参考:springMVC+Redis 集成
接着根据自己使用的Redis模板以及需求实现Cache:
public class RedisCache<K,V> implements Cache<K,V>
实现CacheManager:
public class RedisCacheManager implements CacheManager {
@Override
public <K, V> Cache<K, V> getCache(String s) throws CacheException {
return new RedisCache<>();
}
}
最后把spring-shiro里的cacheManager换成自己实现的RedisCacheManager。