Ehcache學習筆記(1)--spring整合
阿新 • • 發佈:2018-11-14
一:spring整合ehcache
1、spring整合的ehcache是2.10.x版,jar包要對。
<!--ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
2、spring 的xml配置
<bean id="cache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml" /> </bean> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="cache" /> </bean> <cache:annotation-driven cache-manager="cacheManager"/>
3、ehcaceh的xml配置
該配置檔案可以在net.sf.ehcache jar包下找到
ehcache.xml詳細配置參考
<?xml version="1.0" encoding="utf-8" ?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"> <diskStore path="java.io.tmpdir"/> <defaultCache maxEntriesLocalHeap="1000" eternal="false" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="1000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> <cache name="demoCache" maxEntriesLocalHeap="1000" maxEntriesLocalDisk="100" eternal="false" diskSpoolBufferSizeMB="30" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> <persistence strategy="localTempSwap"/> </cache> </ehcache>
4、spring整合ehcache註解的使用demo
@Cacheable(value="demoCache",key="#userName") public User findUserByUserName(String userName){ System.out.println("--------- find user name -----------"); return new User("ke","123654","cccp"); } @CacheEvict(value = "demoCache",key = "#userName") public User removeName(String userName){ System.out.println("--------- delete user name -----------"); return new User("kexq","123654","2009"); }
註解說明:
(1)@Cacheable(value=“demoCache”,key="#userName",condition="")
value:cacheName 不可為空;在ehcache.xml檔案中必須存在的cacheNme
key:springEL表示式編寫
condition:限制條件
(2)@CacheEvict
去除快取
(3)@CachePut
不管對應快取是否存在,都執行方法體,並且將返回的內容寫入快取
(4)@CacheConfig(value=“cacheName”)
類級別的註解,若類中使用快取是同一個,可以配置在此註解中
5、demoTest
@Resource
private LoginService loginService;
@RequestMapping("index.do")
public String index(){
//第一次呼叫時快取,第二次呼叫直接取快取
loginService.findUserByUserName("ke");
loginService.findUserByUserName("ke");
loginService.removeName("ke");
// 刪除後再次呼叫時,再次快取
System.out.println(loginService.findUserByUserName("ke"));
return "index";
}