轉載來自:http://www.cnblogs.com/mxmbk/articles/5162813.html
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的分布式緩存有傳統的RMI,1.5版的JGroups,1.6版的JMS。分布式緩存主要解決集群環境中不同的服務器間的數據的同步問題。
使用Spring的AOP進行整合,可以靈活的對方法的返回結果對象進行緩存。
下面將介紹Spring+EhCache詳細實例。
本實例的環境 eclipse + maven + spring + ehcache + junit
2.1、相關依賴pom.xml
1 <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">
2 <modelVersion>4.0.0</modelVersion>
3 <groupId>com.luo</groupId>
4 <artifactId>ehcache_project</artifactId>
5 <version>0.0.1-SNAPSHOT</version>
6 <properties>
7 <!-- spring版本號 -->
8 <spring.version>3.2.8.RELEASE</spring.version>
9 <!-- junit版本號 -->
10 <junit.version>4.10</junit.version>
11 </properties>
12
13 <dependencies>
14 <!-- 添加Spring依賴 -->
15 <dependency>
16 <groupId>org.springframework</groupId>
17 <artifactId>spring-core</artifactId>
18 <version>${spring.version}</version>
19 </dependency>
20 <dependency>
21 <groupId>org.springframework</groupId>
22 <artifactId>spring-webmvc</artifactId>
23 <version>${spring.version}</version>
24 </dependency>
25 <dependency>
26 <groupId>org.springframework</groupId>
27 <artifactId>spring-context</artifactId>
28 <version>${spring.version}</version>
29 </dependency>
30 <dependency>
31 <groupId>org.springframework</groupId>
32 <artifactId>spring-context-support</artifactId>
33 <version>${spring.version}</version>
34 </dependency>
35 <dependency>
36 <groupId>org.springframework</groupId>
37 <artifactId>spring-aop</artifactId>
38 <version>${spring.version}</version>
39 </dependency>
40 <dependency>
41 <groupId>org.springframework</groupId>
42 <artifactId>spring-aspects</artifactId>
43 <version>${spring.version}</version>
44 </dependency>
45 <dependency>
46 <groupId>org.springframework</groupId>
47 <artifactId>spring-tx</artifactId>
48 <version>${spring.version}</version>
49 </dependency>
50 <dependency>
51 <groupId>org.springframework</groupId>
52 <artifactId>spring-jdbc</artifactId>
53 <version>${spring.version}</version>
54 </dependency>
55 <dependency>
56 <groupId>org.springframework</groupId>
57 <artifactId>spring-web</artifactId>
58 <version>${spring.version}</version>
59 </dependency>
60
61 <!--單元測試依賴 -->
62 <dependency>
63 <groupId>junit</groupId>
64 <artifactId>junit</artifactId>
65 <version>${junit.version}</version>
66 <scope>test</scope>
67 </dependency>
68
69 <!--spring單元測試依賴 -->
70 <dependency>
71 <groupId>org.springframework</groupId>
72 <artifactId>spring-test</artifactId>
73 <version>${spring.version}</version>
74 <scope>test</scope>
75 </dependency>
76
77 <!-- ehcache 相關依賴 -->
78 <dependency>
79 <groupId>net.sf.ehcache</groupId>
80 <artifactId>ehcache</artifactId>
81 <version>2.8.2</version>
82 </dependency>
83 </dependencies>
84 </project>
2.2、添加ehcache配置文件ehcache-setting.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <ehcache> 3 <!-- 指定一個文件目錄,當EhCache把數據寫到硬盤上時,將把數據寫到這個文件目錄下 --> 4 <diskStore path="java.io.tmpdir"/> 5 6 <!-- 設定緩存的默認數據過期策略 --> 7 <defaultCache 8 maxElementsInMemory="10000" 9 eternal="false" 10 overflowToDisk="true" 11 timeToIdleSeconds="10" 12 timeToLiveSeconds="20" 13 diskPersistent="false" 14 diskExpiryThreadIntervalSeconds="120"/> 15 16 <cache name="cacheTest" 17 maxElementsInMemory="1000" 18 eternal="false" 19 overflowToDisk="true" 20 timeToIdleSeconds="10" 21 timeToLiveSeconds="20"/> 22 23 </ehcache>
這裡我們配置了cacheTest策略,10秒過期。
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(最少訪問次數)。
2.3、spring配置文件application.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:cache="http://www.springframework.org/schema/cache" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 12 http://www.springframework.org/schema/context 13 http://www.springframework.org/schema/context/spring-context-3.0.xsd 14 http://www.springframework.org/schema/cache 15 http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"> 16 17 <!-- 自動掃描注解的bean --> 18 <context:component-scan base-package="com.luo.service" /> 19 20 <cache:annotation-driven cache-manager="cacheManager" /> 21 22 <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> 23 <property name="cacheManager" ref="ehcache"></property> 24 </bean> 25 26 <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 27 <property name="configLocation" value="classpath:ehcache-setting.xml"></property> 28 </bean> 29 30 </beans>
2.4、EhCacheTestService接口
1 package com.luo.service;
2
3 public interface EhCacheTestService {
4 public String getTimestamp(String param);
5 }
2.5、EhCacheTestService接口實現
1 package com.luo.service.impl;
2
3 import org.springframework.cache.annotation.Cacheable;
4 import org.springframework.stereotype.Service;
5 import com.luo.service.EhCacheTestService;
6
7 @Service
8 public class EhCacheTestServiceImpl implements EhCacheTestService {
9
10 @Cacheable(value="cacheTest",key="#param")
11 public String getTimestamp(String param) {
12 Long timestamp = System.currentTimeMillis();
13 return timestamp.toString();
14 }
15
16 }
這裡注解中value=”cacheTest”與ehcache-setting.xml中的cache名稱屬性值一致。
2.6、單元測試類
1 package com.luo.baseTest;
2
3 import org.junit.runner.RunWith;
4 import org.springframework.test.context.ContextConfiguration;
5 import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
6 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
7
8 //指定bean注入的配置文件
9 @ContextConfiguration(locations = { "classpath:application.xml" })
10 //使用標准的JUnit @RunWith注釋來告訴JUnit使用Spring TestRunner
11 @RunWith(SpringJUnit4ClassRunner.class)
12 public class SpringTestCase extends AbstractJUnit4SpringContextTests {
13
14 }
15 package com.luo.service;
16
17 import org.junit.Test;
18 import org.springframework.beans.factory.annotation.Autowired;
19
20 import com.luo.baseTest.SpringTestCase;
21
22 public class EhCacheTestServiceTest extends SpringTestCase {
23
24 @Autowired
25 private EhCacheTestService ehCacheTestService;
26
27 @Test
28 public void getTimestampTest() throws InterruptedException{
29 System.out.println("第一次調用:" + ehCacheTestService.getTimestamp("param"));
30 Thread.sleep(2000);
31 System.out.println("2秒之後調用:" + ehCacheTestService.getTimestamp("param"));
32 Thread.sleep(11000);
33 System.out.println("再過11秒之後調用:" + ehCacheTestService.getTimestamp("param"));
34 }
35 }

http://download.csdn.net/detail/u013142781/9401689