Spring搭配Ehcache實(shí)例解析
1 Ehcache簡(jiǎn)介
EhCache 是一個(gè)純Java的進(jìn)程內(nèi)緩存框架,具有快速、精干等特點(diǎn),是Hibernate中默認(rèn)的CacheProvider。
Ehcache是一種廣泛使用的開(kāi)源Java分布式緩存。主要面向通用緩存,Java EE和輕量級(jí)容器。它具有內(nèi)存和磁盤存儲(chǔ),緩存加載器,緩存擴(kuò)展,緩存異常處理程序,一個(gè)gzip緩存servlet過(guò)濾器,支持REST和SOAP api等特點(diǎn)。
Ehcache最初是由Greg Luck于2003年開(kāi)始開(kāi)發(fā)。2009年,該項(xiàng)目被Terracotta購(gòu)買。軟件仍然是開(kāi)源,但一些新的主要功能(例如,快速可重啟性之間的一致性的)只能在商業(yè)產(chǎn)品中使用,例如Enterprise EHCache and BigMemory。維基媒體Foundationannounced目前使用的就是Ehcache技術(shù)。
總之Ehcache還是一個(gè)不錯(cuò)的緩存技術(shù),我們來(lái)看看Spring搭配Ehcache是如何實(shí)現(xiàn)的。
2 Spring搭配Ehcache
系統(tǒng)結(jié)果如下:
3 具體配置介紹
有這幾部分的結(jié)合:
src:java代碼,包含攔截器,調(diào)用接口,測(cè)試類
src/cache-bean.xml:配置Ehcache,攔截器,以及測(cè)試類等信息對(duì)應(yīng)的bean
src/ehcache.xml:Ehcache緩存配置信息
WebRoot/lib:庫(kù)
4 詳細(xì)內(nèi)容介紹
4.1 src
4.1.1 攔截器
代碼中首先配置了兩個(gè)攔截器:
第一個(gè)攔截器為:
com.test.ehcache.CacheMethodInterceptor
內(nèi)容如下:
package com.test.ehcache; import java.io.Serializable; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; public class CacheMethodInterceptor implements MethodInterceptor, InitializingBean { private Cache cache; public void setCache(Cache cache) { this.cache = cache; } public CacheMethodInterceptor() { super(); } /** * 攔截ServiceManager的方法,并查找該結(jié)果是否存在,如果存在就返回cache中的值, * 否則,返回?cái)?shù)據(jù)庫(kù)查詢結(jié)果,并將查詢結(jié)果放入cache */ public Object invoke(MethodInvocation invocation) throws Throwable { //獲取要攔截的類 String targetName = invocation.getThis().getClass().getName(); //獲取要攔截的類的方法 String methodName = invocation.getMethod().getName(); //獲得要攔截的類的方法的參數(shù) Object[] arguments = invocation.getArguments(); Object result; //創(chuàng)建一個(gè)字符串,用來(lái)做cache中的key String cacheKey = getCacheKey(targetName, methodName, arguments); //從cache中獲取數(shù)據(jù) Element element = cache.get(cacheKey); if (element == null) { //如果cache中沒(méi)有數(shù)據(jù),則查找非緩存,例如數(shù)據(jù)庫(kù),并將查找到的放入cache result = invocation.proceed(); //生成將存入cache的key和value element = new Element(cacheKey, (Serializable) result); System.out.println("-----進(jìn)入非緩存中查找,例如直接查找數(shù)據(jù)庫(kù),查找后放入緩存"); //將key和value存入cache cache.put(element); } else { //如果cache中有數(shù)據(jù),則查找cache System.out.println("-----進(jìn)入緩存中查找,不查找數(shù)據(jù)庫(kù),緩解了數(shù)據(jù)庫(kù)的壓力"); } return element.getValue(); } /** * 獲得cache的key的方法,cache的key是Cache中一個(gè)Element的唯一標(biāo)識(shí), * 包括包名+類名+方法名,如:com.test.service.TestServiceImpl.getObject */ private String getCacheKey(String targetName, String methodName, Object[] arguments) { StringBuffer sb = new StringBuffer(); sb.append(targetName).append(".").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { sb.append(".").append(arguments[i]); } } return sb.toString(); } /** * implement InitializingBean,檢查cache是否為空 70 */ public void afterPropertiesSet() throws Exception { Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it."); } }
CacheMethodInterceptor用來(lái)攔截以“get”開(kāi)頭的方法,注意這個(gè)攔截器是先攔截,后執(zhí)行原調(diào)用接口。
還有一個(gè)攔截器:
com.test.ehcache.CacheAfterReturningAdvice
具體內(nèi)容:
package com.test.ehcache; import java.lang.reflect.Method; import java.util.List; import net.sf.ehcache.Cache; import org.springframework.aop.AfterReturningAdvice; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; public class CacheAfterReturningAdvice implements AfterReturningAdvice, InitializingBean { private Cache cache; public void setCache(Cache cache) { this.cache = cache; } public CacheAfterReturningAdvice() { super(); } public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { String className = arg3.getClass().getName(); List list = cache.getKeys(); for (int i = 0; i < list.size(); i++) { String cacheKey = String.valueOf(list.get(i)); if (cacheKey.startsWith(className)) { cache.remove(cacheKey); System.out.println("-----清除緩存"); } } } public void afterPropertiesSet() throws Exception { Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it."); } }
CacheAfterReturningAdvice用來(lái)攔截以“update”開(kāi)頭的方法,注意這個(gè)攔截器是先執(zhí)行原調(diào)用接口,后被攔截。
4.1.2 調(diào)用接口
接口名稱為:
com.test.service.ServiceManager
具體內(nèi)容如下:
package com.test.service; import java.util.List; public interface ServiceManager { public List getObject(); public void updateObject(Object Object); }
實(shí)現(xiàn)類名稱為:
com.test.service.ServiceManagerImpl
具體內(nèi)容如下:
package com.test.service; import java.util.ArrayList; import java.util.List; public class ServiceManagerImpl implements ServiceManager { @Override public List getObject() { System.out.println("-----ServiceManager:緩存Cache內(nèi)不存在該element,查找數(shù)據(jù)庫(kù),并放入Cache!"); return null; } @Override public void updateObject(Object Object) { System.out.println("-----ServiceManager:更新了對(duì)象,這個(gè)類產(chǎn)生的cache都將被remove!"); } }
4.1.3 測(cè)試類
測(cè)試類名稱為:
com.test.service.TestMain
具體內(nèi)容為:
package com.test.service; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestMain { public static void main(String[] args) { String cacheString = "/cache-bean.xml"; ApplicationContext context = new ClassPathXmlApplicationContext( cacheString); //獲取代理工廠proxyFactory生成的bean,以便產(chǎn)生攔截效果 ServiceManager testService = (ServiceManager) context.getBean("proxyFactory"); // 第一次查找 System.out.println("=====第一次查找"); testService.getObject(); // 第二次查找 System.out.println("=====第二次查找"); testService.getObject(); // 執(zhí)行update方法(應(yīng)該清除緩存) System.out.println("=====第一次更新"); testService.updateObject(null); // 第三次查找 System.out.println("=====第三次查找"); testService.getObject(); } }
此處要注意,獲取bean是通過(guò)代理工廠proxyFactory生產(chǎn)的bean,這樣才會(huì)有攔截效果。
能夠看出來(lái),在測(cè)試類里面設(shè)置了四次調(diào)用,執(zhí)行順序?yàn)椋?/p>
第一次查找
第二次查找
第一次更新
第三次查找
4.2 src/cache-bean.xml
cache-bean.xml用來(lái)配置Ehcache,攔截器,以及測(cè)試類等信息對(duì)應(yīng)的bean,內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- 引用ehCache 的配置--> <bean id="defaultCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation"> <value>ehcache.xml</value> </property> </bean> <!-- 定義ehCache的工廠,并設(shè)置所使用的Cache的name,即“com.tt” --> <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <ref local="defaultCacheManager" /> </property> <!-- Cache的名稱 --> <property name="cacheName"> <value>com.tt</value> </property> </bean> <!-- 創(chuàng)建緩存、查詢緩存的攔截器 --> <bean id="cacheMethodInterceptor" class="com.test.ehcache.CacheMethodInterceptor"> <property name="cache"> <ref local="ehCache" /> </property> </bean> <!-- 更新緩存、刪除緩存的攔截器 --> <bean id="cacheAfterReturningAdvice" class="com.test.ehcache.CacheAfterReturningAdvice"> <property name="cache"> <ref local="ehCache" /> </property> </bean> <!-- 調(diào)用接口,被攔截的對(duì)象 --> <bean id="serviceManager" class="com.test.service.ServiceManagerImpl" /> <!-- 插入攔截器,確認(rèn)調(diào)用哪個(gè)攔截器,攔截器攔截的方法名特點(diǎn)等,此處調(diào)用攔截器com.test.ehcache.CacheMethodInterceptor --> <bean id="cachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <!-- 加入切面,切面為當(dāng)執(zhí)行完print方法后,在執(zhí)行加入的切面 --> <property name="advice"> <ref local="cacheMethodInterceptor" /> </property> <property name="patterns"> <list> <!-- ### .表示符合任何單一字元 ### +表示符合前一個(gè)字元一次或多次 ### *表示符合前一個(gè)字元零次或多次 ### \Escape任何Regular expression使用到的符號(hào) --> <!-- .*表示前面的前綴(包括包名),意思是表示getObject方法--> <value>.*get.*</value> </list> </property> </bean> <!-- 插入攔截器,確認(rèn)調(diào)用哪個(gè)攔截器,攔截器攔截的方法名特點(diǎn)等,此處調(diào)用攔截器com.test.ehcache.CacheAfterReturningAdvice --> <bean id="cachePointCutAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="cacheAfterReturningAdvice" /> </property> <property name="patterns"> <list> <!-- .*表示前面的前綴(包括包名),意思是updateObject方法--> <value>.*update.*</value> </list> </property> </bean> <!-- 代理工廠 --> <bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean"> <!-- 說(shuō)明調(diào)用接口bean名稱 --> <property name="target"> <ref local="serviceManager" /> </property> <!-- 說(shuō)明攔截器bean名稱 --> <property name="interceptorNames"> <list> <value>cachePointCut</value> <value>cachePointCutAdvice</value> </list> </property> </bean> </beans>
各個(gè)bean的內(nèi)容都做了注釋說(shuō)明,值得注意的是,不要忘了代理工廠bean。
4.3 src/ehcache.xml
ehcache.xml中存儲(chǔ)Ehcache緩存配置的詳細(xì)信息,內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <!-- 緩存文件位置 --> <diskStore path="D:\\temp\\cache" /> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> <!-- 定義緩存文件信息,其中“com.tt”為緩存文件的名字 --> <cache name="com.tt" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300000" timeToLiveSeconds="600000" overflowToDisk="true" /> </ehcache>
能夠看到緩存的存儲(chǔ)的存儲(chǔ)位置設(shè)置為“D:\temp\cache”,緩存名稱設(shè)置成了“com.tt”,如圖:
4.4 WebRoot/lib
所需的java庫(kù),詳見(jiàn)開(kāi)頭的系統(tǒng)結(jié)構(gòu)圖片,此處略。
5 測(cè)試
執(zhí)行測(cè)試類,測(cè)試結(jié)果如下:
通過(guò)執(zhí)行結(jié)果我們能夠看出:
第一次查找被攔截后發(fā)現(xiàn)是首次攔截,還沒(méi)有緩存Cache,所以先執(zhí)行一下原有接口類,得到要查詢的數(shù)據(jù),有可能是通過(guò)數(shù)據(jù)庫(kù)查詢得到的,然后再生成Cache,并將查詢得到的數(shù)據(jù)放入Cache。
第二次查找被攔截后發(fā)現(xiàn)已經(jīng)存在Cache,于是不再執(zhí)行原有接口類,也就是不再查詢數(shù)據(jù)庫(kù)啦,直接通過(guò)Cache得到查詢數(shù)據(jù)。當(dāng)然這里只是簡(jiǎn)單打印一下。
然后是第一次更新,被攔截后所做的操作是將Cache中的數(shù)據(jù)全部存入數(shù)據(jù)庫(kù),并將Cache刪除。
最后是第三次查詢,被攔截后又發(fā)現(xiàn)系統(tǒng)不存在Cache,于是執(zhí)行原接口類查詢數(shù)據(jù)庫(kù),創(chuàng)建Cache,并將新查詢得到的數(shù)據(jù)放入Cache。同第一次查詢的方式是一樣的。
至此我們就實(shí)現(xiàn)了Spring搭配Ehcache所需要完成的操作。
6 附件源代碼
附件源代碼可以從我的github網(wǎng)站上獲取。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java+swing+Mysql實(shí)現(xiàn)商品銷售管理系統(tǒng)
基礎(chǔ)扎不扎實(shí)只有在實(shí)戰(zhàn)中才能顯現(xiàn),本篇文章手把手帶你用Java+swing+Mysql實(shí)現(xiàn)商品銷售管理系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2022-01-01java實(shí)現(xiàn)屏幕共享功能實(shí)例分析
這篇文章主要介紹了java實(shí)現(xiàn)屏幕共享功能的方法,以實(shí)例形式分析了屏幕共享功能的客戶端與服務(wù)端的詳細(xì)實(shí)現(xiàn)方法,是非常具有實(shí)用價(jià)值的技巧,需要的朋友可以參考下2014-12-12Spring boot通過(guò)切面,實(shí)現(xiàn)超靈活的注解式數(shù)據(jù)校驗(yàn)過(guò)程
這篇文章主要介紹了Spring boot通過(guò)切面,實(shí)現(xiàn)超靈活的注解式數(shù)據(jù)校驗(yàn)過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12如何實(shí)現(xiàn)java Iterator迭代器功能
這篇文章主要介紹了如何實(shí)現(xiàn)java Iterator迭代器功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01Eclipse配置python開(kāi)發(fā)環(huán)境過(guò)程圖解
這篇文章主要介紹了Eclipse配置python開(kāi)發(fā)環(huán)境過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03Spring?@bean和@component注解區(qū)別
本文主要介紹了Spring?@bean和@component注解區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01詳解Spring boot使用Redis集群替換mybatis二級(jí)緩存
本篇文章主要介紹了詳解Spring boot使用Redis集群替換mybatis二級(jí)緩存,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05