Apache Shiro 集成-Ehcache

Shiro中为会话启用Ehcache是非常容易的。首先,确保在你的classpath 中有shiro-ehcache-<version>.jar 文件。

然后,在shiro.ini中配置EHCache为所有Shiro 的缓存提供使用:

[main]

sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO

securityManager.sessionManager.sessionDAO = $sessionDAO

cacheManager = org.apache.shiro.cache.ehcache.EhcacheManager

securityManager.cacheManager = $cacheManager

最后一行,securityManager.cacheManager = $cacheManager,为所有Shiro 的组件配置了一个CacheManager。该CacheManager 实例会自动地直接传送到SessionDAO(通过EnterpriseCacheSessionDAO 实现CacheManagerAware 接口的性质)。

然后,当SessionManager 要求EnterpriseCacheSessionDAO 去持久化一个Session 时,它使用一个EHCache 支持的Cache实现去存储Session 数据。

EHCache Session Cache Configuration

默认地,EhCacheManager 使用一个Shiro 特定的ehcache.xml 文件来建立Session 缓存区以及确保Sessions 正常存取的必要设置。

然而,如果你想改变缓存设置,或想配置你自己的ehcache.xml EHCache net.sf.ehcache.CacheManager 实例,你需要配置缓存区来确保Sessions 被正确地处理。

如果你查看默认的ehcache.xml 文件,你会看到接下来的shiro-activeSessionCache 缓存配置:

<cache name="shiro-activeSessionCache"

   maxElementsInMemory="10000"

   overflowToDisk="true"

   eternal="true"

   timeToLiveSeconds="0"

   timeToIdleSeconds="0"

   diskPersistent="true"

   diskExpiryThreadIntervalSeconds="600"/>

如果你希望使用你自己的ehcache.xml 文件,那么请确保你已经为Shiro 所需定义了一个类似的缓存项。很有可能你会改变maxElementsInMemory 的属性值来吻合你的需要。然而,至少下面两个存在于你自己配置中的属性是非常重要的:

l overflowToDisk="true" - 这确保当你溢出进程内存时,会话不丢失且能够被序列化到磁盘上。

l eternal="true" - 确保缓存项(Session 实例)永不过期或被缓存自动清除。这是很有必要的,因为Shiro 基于计划过程完成自己的验证。如果我们关掉这项,缓存将会在Shiro 不知道的情况下清扫这些Sessions,这可能引起麻烦。

EHCache Session Cache Name

默认地,EnterpriseCacheSessionDAO CacheManager 寻求一个名为"shiro-activeSessionCache"Cache。该缓存的name/region 将在ehcache.xml 中配置,如上所述。

如果你想使用一个不同的名字而不是默认的,你可以在EnterpriseCacheSessionDAO 上配置名字,例如:

[main]

...

sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO

sessionDAO.activeSessionsCacheName = myname

...

只要确保在ehcahe.xml 中有一项与名字匹配且你已经配置好了如上所述的overflowToDisk="true"eternal="true"即可。

Web Applications

需要注意的是,分配SessionDAO是使用Shiro本地的SessionManager实现。在Web应用中默认是使用基于servlet容器的SessionManager不支持SessionDAO。如果你想在web应用中使用基于Ehcache的会话存贮,需要配置web session manager:

main]

...

sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager

securityManager.sessionManager = $sessionManager

# Configure a SessionDAO and then set it:

securityManager.sessionManager.sessionDAO = $sessionDAO


你可能感兴趣的:(Apache Shiro 集成-Ehcache)