shiro許可權控制下的ehcache快取技術總結
---------------------------------------------------------------------------------------
ehcache配置步驟:
1、導包:ehcache的開發包 ehcache-core
spring整合ehcache的包在spring-context-support裡面
2、解壓ehcache-core包,將裡面的 ehcache-failsafe.xml複製並改名為ehcache.xml
自定義快取區,cache標籤後新增name屬性
<!-- 自定義快取 -->
<!-- 複製一份,修改成cache標籤並新增name屬性 -->
<cache name="bos"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
3、配置spring整合ehcache
ehcacheManager交由spring管理,即建立ehcacheManagerFactoryBean
<!-- ehcache快取 -->
<bean id="ehCacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"></property>
</bean>
----------------------------------------------------------------------------------------
shiro整合ehcache的配置步驟:
1、配置shiro封裝快取管理器
<!-- 配置shiro整合快取管理器 -->
<bean id="shiroEhCahceManager"
class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="ehCacheManager"></property>
</bean>
2、將shiro快取管理器注入安全管理器
<!-- 安全管理器 -->
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 自定義的realm -->
<property name="realm" ref="bosRealm"></property>
<property name="cacheManager" ref="shiroEhCahceManager"></property>
</bean>
3、對認證資料、授權資料 自定義的realm進行快取配置
<!-- 配置bosRealm -->
<bean id="bosRealm" class="cn.itcast.bos.realm.BosRealm">
<!-- 對其進行快取配置 -->
<!-- bos為快取cahce.xml中自定義快取配置的name屬性 -->
<property name="authenticationCacheName" value="bos"></property>
</bean>
--------------------------------------------------------------------------------------
注意: 使需要快取物件,實現 Serializable 介面
java.io.NotSerializableException: cn.itcast.bos.domain.system.User
--------------------------------------------------------------------------------------
ehcache對普通業務進行快取
1、spring 封裝cache快取管理器
<!-- spring封裝cache快取管理器 -->
<bean id="springCacheManager"
class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehCacheManager"></property>
</bean>
2、在自定義的applicationContext-cache.xml中引入cache名稱空間
3、啟用spring的快取註解
<!-- spring啟用快取註解 -->
<cache:annotation-driven cache-manager="springCacheManager"/>
4、可以在自定義快取物件類的方法上使用快取註解
@Cacheable 應用快取區,對方法返回結果進行快取 ---- 用於查詢方法
@CacheEvict 清除快取區資料 --- 用於 增加、修改、刪除 方法
針對資料在不同條件下進行不同快取,設定@Cacheable 註解 key 屬性