是五月呀!

shiro开发(六)缓存机制

Shiro提供了类似于Spring的Cache抽象,即Shiro本身不实现Cache,但是对Cache进行了又抽象,方便更换不同的底层Cache实现。

Shiro提供的Cache接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface Cache<K, V> {
//根据Key获取缓存中的值
public V get(K key) throws CacheException;
//往缓存中放入key-value,返回缓存中之前的值
public V put(K key, V value) throws CacheException;
//移除缓存中key对应的值,返回该值
public V remove(K key) throws CacheException;
//清空整个缓存
public void clear() throws CacheException;
//返回缓存大小
public int size();
//获取缓存中所有的key
public Set<K> keys();
//获取缓存中所有的value
public Collection<V> values();
}

Shiro提供的CacheManager接口:

1
2
3
4
public interface CacheManager {
//根据缓存名字获取一个Cache
public <K, V> Cache<K, V> getCache(String name) throws CacheException;
}

Shiro还提供了CacheManagerAware用于注入CacheManager

1
2
3
4
public interface CacheManagerAware {
//注入CacheManager
void setCacheManager(CacheManager cacheManager);
}

Shiro内部相应的组件(DefaultSecurityManager)会自动检测相应的对象(如RealmSessionManager)是否实现了CacheManagerAware并自动注入相应的CacheManager

Realm缓存

Shiro提供了CachingRealm,其实现了CacheManagerAware接口,提供了缓存的一些基础实现;
另外AuthenticatingRealmAuthorizingRealm分别提供了对AuthenticationInfoAuthorizationInfo信息的缓存。

1
2
3
4
5
6
7
8
9
10
11
userRealm=com.xxx.UserRealm
userRealm.cachingEnabled=true
userRealm.authenticationCachingEnabled=true
userRealm.authenticationCacheName=authenticationCache
userRealm.authorizationCachingEnabled=true
userRealm.authorizationCacheName=authorizationCache
securityManager.realms=$userRealm
cacheManager=org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager.cacheManagerConfigFile=classpath:shiro-ehcache.xml
securityManager.cacheManager=$cacheManager
  • userRealm.cachingEnabled:启用缓存,默认false;
  • userRealm.authenticationCachingEnabled:启用身份验证缓存,即缓存AuthenticationInfo信息,默认false;
  • userRealm.authenticationCacheName:缓存AuthenticationInfo信息的缓存名称;
  • userRealm.authorizationCachingEnabled:启用授权缓存,即缓存AuthorizationInfo信息,默认false;
  • userRealm. authorizationCacheName:缓存AuthorizationInfo信息的缓存名称;

Session缓存

当我们设置了SecurityManager的CacheManager时,如:

1
2
3
sessionManager=org.apache.shiro.session.mgt.DefaultSessionManager
securityManager.sessionManager=$sessionManager
securityManager.cacheManager=$cacheManager

securityManager实现了SessionsSecurityManager,其会自动判断SessionManager是否实现了CacheManagerAware接口,如果实现了会把CacheManager设置给它。
然后sessionManager会判断相应的sessionDAO(如继承自CachingSessionDAO)是否实现了CacheManagerAware,如果实现了会把CacheManager设置给它;其会先查缓存,如果找不到才查数据库。

参考:
第十一章 缓存机制——《跟我学Shiro》