【1】Realm缓存
Shiro内部相应的组件(DefaultSecurityManager)会自动检测相应的对象(如Realm)是否实现了CacheManagerAware并自动注入相应的CacheManager。
如项目启动日志:
[INFO][2018-11-06 15:18:18,443][org.apache.shiro.cache.ehcache.EhCacheManager]Cache with name
'com.web.maven.shiro.CustomRealm.authorizationCache' does not yet exist. Creating now.
[INFO][2018-11-06 15:18:18,444][org.apache.shiro.cache.ehcache.EhCacheManager]Added EhCache named
[com.web.maven.shiro.CustomRealm.authorizationCache]
再比如项目运行时:
[INFO][2018-11-06 15:30:20,870][org.apache.shiro.session.mgt.AbstractValidatingSessionManager]Enabling session validation scheduler...
[INFO][2018-11-06 15:30:21,017][org.apache.shiro.cache.ehcache.EhCacheManager]
Using existing EHCache named [shiro-activeSessionCache]
通常在项目中我们会使用自定义的Shiro-ehcache配置文件:
<!-- 缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
</bean>
否则,Shiro将会去加载classpath:org/apache/shiro/cache/ehcache/ehcache.xml
。
Shiro提供了CachingRealm,其实现了CacheManagerAware接口,提供了缓存的一些基础实现。
AuthenticatingRealm及AuthorizingRealm也分别提供了对AuthenticationInfo和AuthorizationInfo信息的缓存。
即,你所看到的Realm是有缓存实现的–CacheManager。如认证过后,在注销前你无需再次认证,授权一次之后在注销前无需再次注销。都是Shiro 缓存在起作用。
如授权和认证缓存配置如下:
<cache name="authorizationCache"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true">
</cache>
<cache name="authenticationCache"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true">
</cache>
【2】Session缓存
如SecurityManager实现了SessionSecurityManager,其会判断SessionManager是否实现了CacheManagerAware接口,如果实现了会把CacheManager设置给它。
SessionManager也会判断相应的SessionDAO(如继承自CachingSessionDAO)是否实现了CacheManagerAware,如果实现了会把CacheManager设置给它。
设置了缓存的SessionManager,查询时会先查缓存,如果找不到才查数据库。
如sessionDao配置:
<!-- Session DAO. 继承 EnterpriseCacheSessionDAO -->
<bean id="sessionDAO"
class="com.web.maven.shiro.MySessionDao">
<property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
<property name="sessionIdGenerator" ref="sessionIdGenerator"/>
</bean>
DefaultSessionManager.applyCacheManagerToSessionDAO()方法源码如下:
private void applyCacheManagerToSessionDAO() {
if (this.cacheManager != null && this.sessionDAO != null && this.sessionDAO instanceof CacheManagerAware) {
((CacheManagerAware) this.sessionDAO).setCacheManager(this.cacheManager);
}
}
通常实际开发中,我们会使用Redis实现Shiro的缓存,不再使用数据库。
参考博文:Shiro会话管理与SessionDao。