Spring搭配Ehcache實例解析
1 Ehcache簡介
EhCache 是一個純Java的進程內(nèi)緩存框架,具有快速、精干等特點,是Hibernate中默認的CacheProvider。
Ehcache是一種廣泛使用的開源Java分布式緩存。主要面向通用緩存,Java EE和輕量級容器。它具有內(nèi)存和磁盤存儲,緩存加載器,緩存擴展,緩存異常處理程序,一個gzip緩存servlet過濾器,支持REST和SOAP api等特點。
Ehcache最初是由Greg Luck于2003年開始開發(fā)。2009年,該項目被Terracotta購買。軟件仍然是開源,但一些新的主要功能(例如,快速可重啟性之間的一致性的)只能在商業(yè)產(chǎn)品中使用,例如Enterprise EHCache and BigMemory。維基媒體Foundationannounced目前使用的就是Ehcache技術(shù)。
總之Ehcache還是一個不錯的緩存技術(shù),我們來看看Spring搭配Ehcache是如何實現(xiàn)的。
2 Spring搭配Ehcache
系統(tǒng)結(jié)果如下:
3 具體配置介紹
有這幾部分的結(jié)合:
src:java代碼,包含攔截器,調(diào)用接口,測試類
src/cache-bean.xml:配置Ehcache,攔截器,以及測試類等信息對應的bean
src/ehcache.xml:Ehcache緩存配置信息
WebRoot/lib:庫
4 詳細內(nèi)容介紹
4.1 src
4.1.1 攔截器
代碼中首先配置了兩個攔截器:
第一個攔截器為:
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中的值, * 否則,返回數(shù)據(jù)庫查詢結(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)建一個字符串,用來做cache中的key String cacheKey = getCacheKey(targetName, methodName, arguments); //從cache中獲取數(shù)據(jù) Element element = cache.get(cacheKey); if (element == null) { //如果cache中沒有數(shù)據(jù),則查找非緩存,例如數(shù)據(jù)庫,并將查找到的放入cache result = invocation.proceed(); //生成將存入cache的key和value element = new Element(cacheKey, (Serializable) result); System.out.println("-----進入非緩存中查找,例如直接查找數(shù)據(jù)庫,查找后放入緩存"); //將key和value存入cache cache.put(element); } else { //如果cache中有數(shù)據(jù),則查找cache System.out.println("-----進入緩存中查找,不查找數(shù)據(jù)庫,緩解了數(shù)據(jù)庫的壓力"); } return element.getValue(); } /** * 獲得cache的key的方法,cache的key是Cache中一個Element的唯一標識, * 包括包名+類名+方法名,如: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用來攔截以“get”開頭的方法,注意這個攔截器是先攔截,后執(zhí)行原調(diào)用接口。
還有一個攔截器:
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用來攔截以“update”開頭的方法,注意這個攔截器是先執(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); }
實現(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ù)庫,并放入Cache!"); return null; } @Override public void updateObject(Object Object) { System.out.println("-----ServiceManager:更新了對象,這個類產(chǎn)生的cache都將被remove!"); } }
4.1.3 測試類
測試類名稱為:
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方法(應該清除緩存) System.out.println("=====第一次更新"); testService.updateObject(null); // 第三次查找 System.out.println("=====第三次查找"); testService.getObject(); } }
此處要注意,獲取bean是通過代理工廠proxyFactory生產(chǎn)的bean,這樣才會有攔截效果。
能夠看出來,在測試類里面設(shè)置了四次調(diào)用,執(zhí)行順序為:
第一次查找
第二次查找
第一次更新
第三次查找
4.2 src/cache-bean.xml
cache-bean.xml用來配置Ehcache,攔截器,以及測試類等信息對應的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)用接口,被攔截的對象 --> <bean id="serviceManager" class="com.test.service.ServiceManagerImpl" /> <!-- 插入攔截器,確認調(diào)用哪個攔截器,攔截器攔截的方法名特點等,此處調(diào)用攔截器com.test.ehcache.CacheMethodInterceptor --> <bean id="cachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <!-- 加入切面,切面為當執(zhí)行完print方法后,在執(zhí)行加入的切面 --> <property name="advice"> <ref local="cacheMethodInterceptor" /> </property> <property name="patterns"> <list> <!-- ### .表示符合任何單一字元 ### +表示符合前一個字元一次或多次 ### *表示符合前一個字元零次或多次 ### \Escape任何Regular expression使用到的符號 --> <!-- .*表示前面的前綴(包括包名),意思是表示getObject方法--> <value>.*get.*</value> </list> </property> </bean> <!-- 插入攔截器,確認調(diào)用哪個攔截器,攔截器攔截的方法名特點等,此處調(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"> <!-- 說明調(diào)用接口bean名稱 --> <property name="target"> <ref local="serviceManager" /> </property> <!-- 說明攔截器bean名稱 --> <property name="interceptorNames"> <list> <value>cachePointCut</value> <value>cachePointCutAdvice</value> </list> </property> </bean> </beans>
各個bean的內(nèi)容都做了注釋說明,值得注意的是,不要忘了代理工廠bean。
4.3 src/ehcache.xml
ehcache.xml中存儲Ehcache緩存配置的詳細信息,內(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>
能夠看到緩存的存儲的存儲位置設(shè)置為“D:\temp\cache”,緩存名稱設(shè)置成了“com.tt”,如圖:
4.4 WebRoot/lib
所需的java庫,詳見開頭的系統(tǒng)結(jié)構(gòu)圖片,此處略。
5 測試
執(zhí)行測試類,測試結(jié)果如下:
通過執(zhí)行結(jié)果我們能夠看出:
第一次查找被攔截后發(fā)現(xiàn)是首次攔截,還沒有緩存Cache,所以先執(zhí)行一下原有接口類,得到要查詢的數(shù)據(jù),有可能是通過數(shù)據(jù)庫查詢得到的,然后再生成Cache,并將查詢得到的數(shù)據(jù)放入Cache。
第二次查找被攔截后發(fā)現(xiàn)已經(jīng)存在Cache,于是不再執(zhí)行原有接口類,也就是不再查詢數(shù)據(jù)庫啦,直接通過Cache得到查詢數(shù)據(jù)。當然這里只是簡單打印一下。
然后是第一次更新,被攔截后所做的操作是將Cache中的數(shù)據(jù)全部存入數(shù)據(jù)庫,并將Cache刪除。
最后是第三次查詢,被攔截后又發(fā)現(xiàn)系統(tǒng)不存在Cache,于是執(zhí)行原接口類查詢數(shù)據(jù)庫,創(chuàng)建Cache,并將新查詢得到的數(shù)據(jù)放入Cache。同第一次查詢的方式是一樣的。
至此我們就實現(xiàn)了Spring搭配Ehcache所需要完成的操作。
6 附件源代碼
附件源代碼可以從我的github網(wǎng)站上獲取。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java+swing+Mysql實現(xiàn)商品銷售管理系統(tǒng)
基礎(chǔ)扎不扎實只有在實戰(zhàn)中才能顯現(xiàn),本篇文章手把手帶你用Java+swing+Mysql實現(xiàn)商品銷售管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2022-01-01Spring boot通過切面,實現(xiàn)超靈活的注解式數(shù)據(jù)校驗過程
這篇文章主要介紹了Spring boot通過切面,實現(xiàn)超靈活的注解式數(shù)據(jù)校驗過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Eclipse配置python開發(fā)環(huán)境過程圖解
這篇文章主要介紹了Eclipse配置python開發(fā)環(huán)境過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03Spring?@bean和@component注解區(qū)別
本文主要介紹了Spring?@bean和@component注解區(qū)別,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01詳解Spring boot使用Redis集群替換mybatis二級緩存
本篇文章主要介紹了詳解Spring boot使用Redis集群替換mybatis二級緩存,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05