Spring+EHcache緩存實(shí)例詳解
一、ehcahe的介紹
EhCache 是一個(gè)純Java的進(jìn)程內(nèi)緩存框架,具有高速、精干等特點(diǎn),是Hibernate中默認(rèn)的CacheProvider。Ehcache是一種廣泛使用的開(kāi)源Java分布式緩存。
主要面向通用緩存,Java EE和輕量級(jí)容器。
它具有內(nèi)存和磁盤(pán)存儲(chǔ)。緩存載入器,緩存擴(kuò)展,緩存異常處理程序,一個(gè)gzip緩存servlet過(guò)濾器。支持REST和SOAP api等特點(diǎn)。
優(yōu)點(diǎn):
1. 高速
2. 簡(jiǎn)單
3. 多種緩存策略
4. 緩存數(shù)據(jù)有兩級(jí):內(nèi)存和磁盤(pán),因此無(wú)需操心容量問(wèn)題
5. 緩存數(shù)據(jù)會(huì)在虛擬機(jī)重新啟動(dòng)的過(guò)程中寫(xiě)入磁盤(pán)
6. 能夠通過(guò)RMI、可插入API等方式進(jìn)行分布式緩存
7. 具有緩存和緩存管理器的偵聽(tīng)接口
8. 支持多緩存管理器實(shí)例,以及一個(gè)實(shí)例的多個(gè)緩存區(qū)域
9. 提供Hibernate的緩存實(shí)現(xiàn)
缺點(diǎn):
1. 使用磁盤(pán)Cache的時(shí)候很占用磁盤(pán)空間:這是由于DiskCache的算法簡(jiǎn)單。該算法簡(jiǎn)單也導(dǎo)致Cache的效率很高。它僅僅是對(duì)元素直接追加存儲(chǔ)。因此搜索元素的時(shí)候很的快。假設(shè)使用DiskCache的,在很頻繁的應(yīng)用中,很快磁盤(pán)會(huì)滿。
2. 不能保證數(shù)據(jù)的安全:當(dāng)突然kill掉java的時(shí)候,可能會(huì)產(chǎn)生沖突,EhCache的解決方法是假設(shè)文件沖突了。則重建cache。這對(duì)于Cache數(shù)據(jù)須要保存的時(shí)候可能不利。當(dāng)然,Cache僅僅是簡(jiǎn)單的加速。而不能保證數(shù)據(jù)的安全。假設(shè)想保證數(shù)據(jù)的存儲(chǔ)安全,能夠使用Bekeley DB Java Edition版本號(hào)。
這是個(gè)嵌入式數(shù)據(jù)庫(kù)。能夠確保存儲(chǔ)安全和空間的利用率。
EhCache的分布式緩存有傳統(tǒng)的RMI,1.5版的JGroups,1.6版的JMS。分布式緩存主要解決集群環(huán)境中不同的server間的數(shù)據(jù)的同步問(wèn)題。
使用Spring的AOP進(jìn)行整合,能夠靈活的對(duì)方法的返回結(jié)果對(duì)象進(jìn)行緩存。
以下將介紹Spring+EhCache具體實(shí)例。
二、具體實(shí)例解說(shuō)
本實(shí)例的環(huán)境 eclipse + maven + spring + ehcache + junit
2.1、相關(guān)依賴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版本號(hào)號(hào) --> <spring.version>3.2.8.RELEASE</spring.version> <!-- junit版本號(hào)號(hào) --> <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> <!--單元測(cè)試依賴 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!--spring單元測(cè)試依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- ehcache 相關(guān)依賴 --> <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> <!-- 指定一個(gè)文件文件夾,當(dāng)EhCache把數(shù)據(jù)寫(xiě)到硬盤(pán)上時(shí)。將把數(shù)據(jù)寫(xiě)到這個(gè)文件文件夾下 --> <diskStore path="java.io.tmpdir"/> <!-- 設(shè)定緩存的默認(rèn)數(shù)據(jù)過(guò)期策略 --> <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秒過(guò)期。
cache元素的屬性:
name:緩存名稱
maxElementsInMemory:內(nèi)存中最大緩存對(duì)象數(shù)
maxElementsOnDisk:硬盤(pán)中最大緩存對(duì)象數(shù)。若是0表示無(wú)窮大
eternal:true表示對(duì)象永只是期,此時(shí)會(huì)忽略timeToIdleSeconds和timeToLiveSeconds屬性。默覺(jué)得false
overflowToDisk:true表示當(dāng)內(nèi)存緩存的對(duì)象數(shù)目達(dá)到了
maxElementsInMemory界限后。會(huì)把溢出的對(duì)象寫(xiě)到硬盤(pán)緩存中。注意:假設(shè)緩存的對(duì)象要寫(xiě)入到硬盤(pán)中的話。則該對(duì)象必須實(shí)現(xiàn)了Serializable接口才行。
diskSpoolBufferSizeMB:磁盤(pán)緩存區(qū)大小,默覺(jué)得30MB。
每一個(gè)Cache都應(yīng)該有自己的一個(gè)緩存區(qū)。
diskPersistent:是否緩存虛擬機(jī)重新啟動(dòng)期數(shù)據(jù)。是否持久化磁盤(pán)緩存,當(dāng)這個(gè)屬性的值為true時(shí),系統(tǒng)在初始化時(shí)會(huì)在磁盤(pán)中查找文件名稱為cache名稱,后綴名為index的文件,這個(gè)文件里存放了已經(jīng)持久化在磁盤(pán)中的cache的index,找到后會(huì)把cache載入到內(nèi)存,要想把cache真正持久化到磁盤(pán),敲代碼時(shí)注意執(zhí)行net.sf.ehcache.Cache.put(Element element)后要調(diào)用flush()方法。
diskExpiryThreadIntervalSeconds:磁盤(pán)失效線程執(zhí)行時(shí)間間隔。默覺(jué)得120秒
timeToIdleSeconds: 設(shè)定同意對(duì)象處于空暇狀態(tài)的最長(zhǎng)時(shí)間,以秒為單位。當(dāng)對(duì)象自從近期一次被訪問(wèn)后,假設(shè)處于空暇狀態(tài)的時(shí)間超過(guò)了timeToIdleSeconds屬性值,這個(gè)對(duì)象就會(huì)過(guò)期,EHCache將把它從緩存中清空。僅僅有當(dāng)eternal屬性為false,該屬性才有效。假設(shè)該屬性值為0,則表示對(duì)象能夠無(wú)限期地處于空暇狀態(tài)
timeToLiveSeconds:設(shè)定對(duì)象同意存在于緩存中的最長(zhǎng)時(shí)間,以秒為單位。
當(dāng)對(duì)象自從被存放到緩存中后,假設(shè)處于緩存中的時(shí)間超過(guò)了 timeToLiveSeconds屬性值,這個(gè)對(duì)象就會(huì)過(guò)期。EHCache將把它從緩存中清除。
僅僅有當(dāng)eternal屬性為false,該屬性才有效。
假設(shè)該屬性值為0,則表示對(duì)象能夠無(wú)限期地存在于緩存中。
timeToLiveSeconds必須大于timeToIdleSeconds屬性,才有意義
memoryStoreEvictionPolicy:當(dāng)達(dá)到maxElementsInMemory限制時(shí)。Ehcache將會(huì)依據(jù)指定的策略去清理內(nèi)存。可選策略有:LRU(近期最少使用,默認(rèn)策略)、FIFO(先進(jìn)先出)、LFU(最少訪問(wèn)次數(shù))。
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"> <!-- 自己主動(dòng)掃描注解的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接口實(shí)現(xiàn)
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、單元測(cè)試類
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" }) //使用標(biāo)準(zhǔn)的JUnit @RunWith凝視來(lái)告訴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("第一次調(diào)用:" + ehCacheTestService.getTimestamp("param")); Thread.sleep(2000); System.out.println("2秒之后調(diào)用:" + ehCacheTestService.getTimestamp("param")); Thread.sleep(11000); System.out.println("再過(guò)11秒之后調(diào)用:" + ehCacheTestService.getTimestamp("param")); } }
2.7、執(zhí)行結(jié)果
三、工程源代碼下載
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java優(yōu)化hibernate性能的幾點(diǎn)建議
以上是在進(jìn)行struts+hibernate+spring進(jìn)行項(xiàng)目開(kāi)發(fā)中,對(duì)hibernate性能優(yōu)化的幾點(diǎn)心得。2008-10-10關(guān)于ThreadLocal對(duì)request和response的用法說(shuō)明
這篇文章主要介紹了關(guān)于ThreadLocal對(duì)request和response的用法說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08ConcurrentModificationException日志關(guān)鍵字報(bào)警思考分析
本文將記錄和分析日志中的ConcurrentModificationException關(guān)鍵字報(bào)警,還有一些我的思考,有需要的朋友可以借鑒參考下,希望能夠有所幫助2023-12-12Feign調(diào)用服務(wù)時(shí)丟失Cookie和Header信息的解決方案
這篇文章主要介紹了Feign調(diào)用服務(wù)時(shí)丟失Cookie和Header信息的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Java 單鏈表數(shù)據(jù)結(jié)構(gòu)的增刪改查教程
這篇文章主要介紹了Java 單鏈表數(shù)據(jù)結(jié)構(gòu)的增刪改查教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10java發(fā)送郵件及打開(kāi)狀態(tài)判斷分析實(shí)例
這篇文章主要為大家介紹了java發(fā)送郵件及打開(kāi)狀態(tài)判斷分析實(shí)例2023-12-12