一、EhCache介紹
EhCache 是一個純Java的進程內緩存框架,具有快速、精干等特點,是Hibernate中默認的CacheProvider。Ehcache是一種廣泛使用的開 源Java分布式緩存。主要面向通用緩存,Java EE和輕量級容器。它具有內存和磁盤存儲,緩存加載器,緩存擴展,緩存異常處理程序,一個gzip緩存servlet過濾器,支持REST和SOAP api等特點。
優點:
1. 快速
2. 簡單
3. 多種緩存策略
4. 緩存數據有兩級:內存和磁盤,因此無需擔心容量問題
5. 緩存數據會在虛擬機重啟的過程中寫入磁盤
6. 可以通過RMI、可插入API等方式進行分布式緩存
7. 具有緩存和緩存管理器的偵聽接口
8. 支持多緩存管理器實例,以及一個實例的多個緩存區域
9. 提供Hibernate的緩存實現
缺點:
1. 使用磁盤Cache的時候非常占用磁盤空間:這是因為DiskCache的算法簡單,該算法簡單也導致Cache的效率非常高。它只是對元素直接追加存儲。因此搜索元素的時候非常的快。如果使用DiskCache的,在很頻繁的應用中,很快磁盤會滿。
2. 不能保證數據的安全:當突然kill掉java的時候,可能會產生沖突,EhCache的解決方法是如果文件沖突了,則重建cache。這對於Cache 數據需要保存的時候可能不利。當然,Cache只是簡單的加速,而不能保證數據的安全。如果想保證數據的存儲安全,可以使用Bekeley DB Java Edition版本。這是個嵌入式數據庫。可以確保存儲安全和空間的利用率。
ehcache 和 redis 比較:
1. ehcache直接在jvm虛擬機中緩存,速度快,效率高;但是緩存共享麻煩,集群分布式應用不方便。
2. redis是通過socket訪問到緩存服務,效率比ecache低,比數據庫要快很多,處理集群和分布式緩存方便,有成熟的方案。如果是單個應用或者對緩存訪問要求很高的應用,用ehcache。如果是大型系統,存在緩存共享、分布式部署、緩存內容很大的,建議用redis。
3. ehcache也有緩存共享方案,不過是通過RMI或者Jgroup多播方式進行廣播緩存通知更新,緩存共享復雜,維護不方便;簡單的共享可以,但是涉及到緩存恢復,大數據緩存,則不合適。
二、整合詳解
環境:idea + maven + spring + ehcache + junit
1、添加相關依賴(pom.xml)

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>top.jimc</groupId> <artifactId>spring-ehcache-test</artifactId> <version>1.0-SNAPSHOT</version> <description>Spring整合Ehcache測試項目</description> <properties> <junit.version>4.12</junit.version> <spring.version>4.2.5.RELEASE</spring.version> <aspectj.version>1.8.8</aspectj.version> <ehcache.version>2.8.2</ehcache.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.6.6</slf4j.version> </properties> <dependencies> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--對AspectJ支持,面向切面編程,需要外部依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <!-- ehcache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> <!-- 日志工具 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> </dependencies> </project>
2、添加ehcache配置文件ehcache.xml
默認情況下Ehcache會自動加載classpath根目錄下名為ehcache.xml文件,也可以將該文件放到其他地方在使用時指定文件的位置。

<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <!-- 磁盤緩存位置:當EhCache把數據寫到硬盤上時,將把數據寫到這個文件目錄下 --> <diskStore path="java.io.tmpdir"/> <!-- 設定緩存的默認數據過期策略 --> <defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> <!-- 10秒過期,只能緩存20秒 --> <cache name="cacheTest" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="10" timeToLiveSeconds="20" overflowToDisk="true" /> <!-- 緩存半小時 --> <cache name="halfHour" maxElementsInMemory="10000" maxElementsOnDisk="100000" eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="1800" overflowToDisk="true" diskPersistent="false" /> <!-- 緩存一小時 --> <cache name="oneHour" maxElementsInMemory="10000" maxElementsOnDisk="100000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" diskPersistent="false" /> <!-- 緩存一天 --> <cache name="oneDay" maxElementsInMemory="10000" maxElementsOnDisk="100000" eternal="false" timeToIdleSeconds="86400" timeToLiveSeconds="86400" overflowToDisk="true" diskPersistent="false" /> </ehcache>
cache元素屬性說明:
name:緩存名稱
maxElementsInMemory:內存中最大緩存對象數
maxElementsOnDisk:硬盤中最大緩存對象數,若是0表示無窮大
eternal:true表示對象永不過期,此時會忽略timeToIdleSeconds和timeToLiveSeconds屬性,默認為false
overflowToDisk:true表示當內存緩存的對象數目達到了maxElementsInMemory界限后,會把溢出的對象寫到硬盤緩存中。注意:如果緩存的對象要寫入到硬盤中的話,則該對象必須實現了Serializable接口才行。
diskSpoolBufferSizeMB:磁盤緩存區大小,默認為30MB。每個Cache都應該有自己的一個緩存區。
diskPersistent:是否緩存虛擬機重啟期數據,是否持久化磁盤緩存,當這個屬性的值為true時,系統在初始化時會在磁盤中查找文件名 為cache名稱,后綴名為index的文件,這個文件中存放了已經持久化在磁盤中的cache的index,找到后會把cache加載到內存,要想把 cache真正持久化到磁盤,寫程序時注意執行net.sf.ehcache.Cache.put(Element element)后要調用flush()方法。
diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認為120秒。
timeToIdleSeconds: 設定允許對象處於空閑狀態的最長時間,以秒為單位。當對象自從最近一次被訪問后,如果處於空閑狀態的時間超過了timeToIdleSeconds屬性 值,這個對象就會過期,EHCache將把它從緩存中清空。只有當eternal屬性為false,該屬性才有效。如果該屬性值為0,則表示對象可以無限 期地處於空閑狀態。
timeToLiveSeconds:設定對象允許存在於緩存中的最長時間,以秒為單位。當對象自從被存放到緩存中后,如果處於緩存中的時間超過了 timeToLiveSeconds屬性值,這個對象就會過期,EHCache將把它從緩存中清除。只有當eternal屬性為false,該屬性才有 效。如果該屬性值為0,則表示對象可以無限期地存在於緩存中。timeToLiveSeconds必須大於timeToIdleSeconds屬性,才有意義。
memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數)。
3、添加spring配置文件application.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:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/beans/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <context:component-scan base-package="top.jimc.ehcache.service"/> <!-- Spring提供的基於的Ehcache實現的緩存管理器 --> <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml"/> </bean> <bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcacheManager"/> </bean> <!-- cache注解 --> <cache:annotation-driven cache-manager="springCacheManager"/> </beans>
4、創建EhcacheService接口

package top.jimc.ehcache.service; import top.jimc.ehcache.po.User; /** * @author Jimc. * @since 2018/9/21. */ public interface EhcacheService { String getTimestamp(String param); String getDataFromDB(String key); void removeDataAtDB(String key); String refreshData(String key); User findUserById(String userId); void removeUserById(String userId); void removeAllUser(); }
5、創建EhcacheServiceImpl實現類

package top.jimc.ehcache.service.impl; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import top.jimc.ehcache.po.User; import top.jimc.ehcache.service.EhcacheService; /** * @author Jimc. * @since 2018/9/21. */ @Service public class EhcacheServiceImpl implements EhcacheService { @Cacheable(value = "cacheTest", key = "#param") public String getTimestamp(String param) { return String.valueOf(System.currentTimeMillis()); } @Cacheable(value = "cacheTest", key = "#key") public String getDataFromDB(String key) { System.out.println("模擬從數據庫中獲取數據..."); return key + ":" + String.valueOf(Math.round(Math.random()*1000000)); } @CacheEvict(value = "cacheTest", key = "#key") public void removeDataAtDB(String key) { System.out.println("模擬從數據庫中刪除數據..."); } @CachePut(value = "cacheTest", key = "#key") public String refreshData(String key) { System.out.println("模擬從數據庫中加載數據..."); return key + "::" + String.valueOf(Math.round(Math.random()*1000000)); } @Cacheable(value = "cacheTest", key = "'user:' + #userId") public User findUserById(String userId) { System.out.println("模擬從數據庫中查詢數據"); return new User(userId, "Tom"); } /** * 清除cacheTest中指定key的緩存 */ @CacheEvict(value = "cacheTest", key = "'user:' + #userId") public void removeUserById(String userId) { System.out.println("cacheTest remove:" + userId); } /** * 清除cacheTest中全部緩存 */ @CacheEvict(value = "cacheTest", allEntries = true) public void removeAllUser() { System.out.println("cacheTest remove all"); } }
6、創建spring單元測試基類BaseJunit4Test

import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * 測試基類 * @author Jimc. * @since 2018/9/21. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class BaseJunit4Test { }
7、創建測試類EhcacheServiceTest

import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import top.jimc.ehcache.service.EhcacheService; /** * @author Jimc. * @since 2018/9/21. */ public class EhcacheServiceTest extends BaseJunit4Test { @Autowired private EhcacheService ehcacheService; @Test public void testTimestamp() throws InterruptedException { System.out.println("第一次調用:" + ehcacheService.getTimestamp("param")); Thread.sleep(4000); System.out.println("再過4秒之后調用:" + ehcacheService.getTimestamp("param")); Thread.sleep(11000); System.out.println("再過11秒之后調用:" + ehcacheService.getTimestamp("param")); } @Test public void testDataCache() { String key = "LiSi"; String value = ehcacheService.getDataFromDB(key);// 模擬從數據庫中獲取數據 System.out.println(value); value = ehcacheService.getDataFromDB(key);// 從緩存中獲取數據,所以不執行該方法體 System.out.println(value); ehcacheService.removeDataAtDB(key);// 從數據庫中刪除數據 value = ehcacheService.getDataFromDB(key); // 再次從數據庫中獲取數據(緩存數據刪除了,所以要重新獲取,執行方法體) System.out.println(value); } @Test public void testDataPut() { String key = "WangWu"; String value = ehcacheService.refreshData(key);// 模擬從數據庫中加載數據 System.out.println(value); value = ehcacheService.getDataFromDB(key);// 從緩存中獲取數據,所以不執行該方法體 System.out.println(value); value = ehcacheService.refreshData(key);// 再次模擬從數據庫中加載數據,此時會執行方法體 System.out.println(value); value = ehcacheService.getDataFromDB(key);// 從緩存中獲取數據,所以不執行該方法體 System.out.println(value); } @Test public void testFindById(){ System.out.println(ehcacheService.findUserById("1"));// 先模擬從數據庫中查詢數據 System.out.println(ehcacheService.findUserById("1"));// 從緩存中取數據,不會執行方法體 } @Test public void testRemoveUserById(){ System.out.println(ehcacheService.findUserById("1"));// 先添加到緩存 ehcacheService.removeUserById("1");// 再刪除 System.out.println(ehcacheService.findUserById("1")); // 再查詢,如果不存在會執行方法體 } @Test public void testRemoveAllUser(){ // 先模擬從數據庫中查詢數據 System.out.println(ehcacheService.findUserById("1")); System.out.println(ehcacheService.findUserById("2")); ehcacheService.removeAllUser();// 清除cacheTest中全部緩存 // 重新模擬從數據庫中查詢數據,此時執行了方法體,證明緩存中的數據已被清除 System.out.println(ehcacheService.findUserById("1")); System.out.println(ehcacheService.findUserById("2")); } }
8、執行結果

testTimestamp()執行結果: 第一次調用:1537515009017 再過4秒之后調用:1537515009017 再過11秒之后調用:1537515024027 testDataCache()執行結果: 模擬從數據庫中獲取數據... LiSi:477475 LiSi:477475 模擬從數據庫中刪除數據... 模擬從數據庫中獲取數據... LiSi:308969 testDataPut()執行結果: 模擬從數據庫中加載數據... WangWu::77005 WangWu::77005 模擬從數據庫中加載數據... WangWu::539514 WangWu::539514 testFindById()執行結果: 模擬從數據庫中查詢數據 top.jimc.ehcache.po.User@6736fa8d top.jimc.ehcache.po.User@6736fa8d testRemoveUserById()執行結果: 模擬從數據庫中查詢數據 top.jimc.ehcache.po.User@6736fa8d cacheTest remove:1 模擬從數據庫中查詢數據 top.jimc.ehcache.po.User@50313382 testRemoveAllUser()執行結果: 模擬從數據庫中查詢數據 top.jimc.ehcache.po.User@6736fa8d 模擬從數據庫中查詢數據 top.jimc.ehcache.po.User@52815fa3 cacheTest remove all 模擬從數據庫中查詢數據 top.jimc.ehcache.po.User@1cb346ea 模擬從數據庫中查詢數據 top.jimc.ehcache.po.User@4c012563
9、注解基本使用詳解
Spring對緩存的支持類似於對事務的支持。
首先使用注解標記方法,相當於定義了切點,然后使用Aop技術在這個方法的調用前、調用后獲取方法的入參和返回值,進而實現了緩存的邏輯。
(1)@Cacheable
表明所修飾的方法是可以緩存的:當第一次調用這個方法時,它的結果會被緩存下來,在緩存的有效時間內,以后訪問這個方法都直接返回緩存結果,不再執行方法中的代碼段。
這個注解可以用condition屬性來設置條件,如果不滿足條件,就不使用緩存能力,直接執行方法。
可以使用key屬性來指定key的生成規則。
參數:
- alue:緩存位置名稱,不能為空,如果使用EHCache,就是ehcache.xml中聲明的cache的name, 指明將值緩存到哪個Cache中
- key:緩存的key,默認為空,既表示使用方法的參數類型及參數值作為key,支持SpEL,如果要引用參數值使用井號加參數名,如:#userId,一般來說,我們的更新操作只需要刷新緩存中某一個值,所以定義緩存的key值的方式就很重要,最好是能夠唯一,因為這樣可以准確的清除掉特定的緩存,而不會影響到其它緩存值 , 本例子中使用實體加冒號再加ID組合成鍵的名稱,如”user:1”、”order:223123”等
- condition:觸發條件,只有滿足條件的情況才會加入緩存,默認為空,既表示全部都加入緩存,支持SpEL
(2)@CachePut
與@Cacheable不同,@CachePut不僅會緩存方法的結果,還會執行方法的代碼段。它支持的屬性和用法都與@Cacheable一致。
(3)@CacheEvict
與@Cacheable功能相反,@CacheEvict表明所修飾的方法是用來刪除失效或無用的緩存數據。
參數:
- value:緩存位置名稱,不能為空,同上
- key:緩存的key,默認為空,同上
- condition:觸發條件,只有滿足條件的情況才會清除緩存,默認為空,支持SpEL
- allEntries:true表示清除value中的全部緩存,默認為false