一、ehcahe的介紹
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
<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>com.luo</groupId> <artifactId>ehcache_project</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <!-- spring版本号 --> <spring.version>3.2.8.RELEASE</spring.version> <!-- junit版本号 --> <junit.version>4.10</junit.version> </properties> <dependencies> <!-- 添加Spring依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</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-web</artifactId> <version>${spring.version}</version> </dependency> <!--單元測試依賴 --> <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> <!-- ehcache 相關依賴 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.8.2</version> </dependency> </dependencies> </project>
2.2、添加ehcache配置檔案ehcache-setting.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!-- 指定一個檔案目錄,當EhCache把資料寫到硬碟上時,将把資料寫到這個檔案目錄下 --> <diskStore path="java.io.tmpdir"/> <!-- 設定緩存的預設資料過期政策 --> <defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"/> <cache name="cacheTest" maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20"/> </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
<?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" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"> <!-- 自動掃描注解的bean --> <context:component-scan base-package="com.luo.service" /> <cache:annotation-driven cache-manager="cacheManager" /> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcache"></property> </bean> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache-setting.xml"></property> </bean> </beans>
2.4、EhCacheTestService接口
package com.luo.service;
public interface EhCacheTestService {
public String getTimestamp(String param); }
2.5、EhCacheTestService接口實作
package com.luo.service.impl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.luo.service.EhCacheTestService; @Service public class EhCacheTestServiceImpl implements EhCacheTestService { @Cacheable(value="cacheTest",key="#param") public String getTimestamp(String param) { Long timestamp = System.currentTimeMillis(); return timestamp.toString(); } }
這裡注解中value=”cacheTest”與ehcache-setting.xml中的cache名稱屬性值一緻。
2.6、單元測試類
package com.luo.baseTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //指定bean注入的配置檔案 @ContextConfiguration(locations = { "classpath:application.xml" }) //使用标準的JUnit @RunWith注釋來告訴JUnit使用Spring TestRunner @RunWith(SpringJUnit4ClassRunner.class) public class SpringTestCase extends AbstractJUnit4SpringContextTests { }
package com.luo.service;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.luo.baseTest.SpringTestCase; public class EhCacheTestServiceTest extends SpringTestCase { @Autowired private EhCacheTestService ehCacheTestService; @Test public void getTimestampTest() throws InterruptedException{ System.out.println("第一次調用:" + ehCacheTestService.getTimestamp("param")); Thread.sleep("2秒之後調用:" + ehCacheTestService.getTimestamp("param")); Thread.sleep("再過11秒之後調用:" + ehCacheTestService.getTimestamp("param")); } }
2.7、運作結果