<cache:annotation-driven cache-manager="cacheManager" />//開啓緩存註解
緩存配置 <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cache-manager-ref="ehcache">
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:config-location="classpath:spring-ehcache.xml" p:shared="true"/>
緩存設置<?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">
<!-- 設置緩存文件 .data 的創建路徑。
如果該路徑是 Java 系統參數,當前虛擬機會重新賦值。
下面的參數這樣解釋:
user.home – 用戶主目錄
user.dir – 用戶當前工作目錄
java.io.tmpdir – 默認臨時文件路徑 -->
<diskStore path="java.io.tmpdir"/>
<!--缺省緩存配置。CacheManager 會把這些配置應用到程序中。
下列屬性是 defaultCache 必須的:
maxInMemory - 設定內存中創建對象的最大值。
eternal - 設置元素(譯註:內存中對象)是否永久駐留。如果是,將忽略超
時限制且元素永不消亡。
timeToIdleSeconds - 設置某個元素消亡前的停頓時間。
也就是在一個元素消亡之前,兩次訪問時間的最大時間間隔值。
這只能在元素不是永久駐留時有效(譯註:如果對象永恆不滅,則
設置該屬性也無用)。
如果該值是 0 就意味着元素可以停頓無窮長的時間。
timeToLiveSeconds - 爲元素設置消亡前的生存時間。
也就是一個元素從構建到消亡的最大時間間隔值。
這只能在元素不是永久駐留時有效。
overflowToDisk - 設置當內存中緩存達到 maxInMemory 限制時元素是否可寫到磁盤
上。
-->
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5000"
timeToLiveSeconds="5000"
overflowToDisk="true"
/>
<cache name="eLearnCache"
maxElementsInMemory="10"
eternal="false"
timeToIdleSeconds="200"
timeToLiveSeconds="300"
overflowToDisk="true"
/>
</ehcache>
緩存實現
@Cacheable(value="eLearnCache",key="#root.args[0]+'findByName'")
@Query("select u from User u where u.name = ?1")
public User findByName(String name);
緩存測試
System.out.println(loginService.findByName(user.getName()));
System.out.println(loginService.findByName(user.getName()));
測試結果com.spring.entity.User@911ed70
com.spring.entity.User@911ed70
對象一致,說明緩存注入成功,對於緩存的更新要先清除緩存,以及key值得設置,筆者不一一贅述。