1.導入jar包(pom.xml文件)
<!-- ehcache緩存框架 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.11</version> </dependency>
Spring 整合 ehcache 包 spring-context-support 包
2.使用 ehcache ,導入 ehcache.xml 配置文件
解壓 ehcache-core.jar 包 ,將 ehcache-failsafe.xml 復制 src/main/resources
改名 ehcache.xml
ehcache.xml文件
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <!-- 默認緩存區 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> <!-- 自定義緩存區 --> <cache name="bos" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </cache> <!-- 自定義緩存區 --> <cache name="standard" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </cache> </ehcache>
|
3.applicationContext-ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd "> <!-- 緩存配置 --> <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml" /> </bean> <!-- shiro封裝cacheManager --> <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManager" ref="ehCacheManager" /> </bean> <!-- spring 封裝ehcache緩存管理器 --> <bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehCacheManager" /> </bean> <!-- 激活spring 緩存注解 --> <cache:annotation-driven cache-manager="springCacheManager"/> </beans>
加載該配置文件
4.修改web.xml文件
<!-- spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
5.將cache管理器注入到安全管理器中
6.對認證數據、授權數據 哪些進行緩存 ?
對應到ehcache.xml文件中的自定義的緩存緩存區
注意: 使需要緩存對象,實現 Serializable 接口
使用注解進行開發
第七步: 在被 spring 管理 bean 對象方法上 使用@Cacheable 、@CacheEvict
@Cacheable 應用緩存區,對方法返回結果進行緩存 ---- 用於查詢方法
@CacheEvict 清除緩存區數據 --- 用於 增加、修改、刪除 方法