Spring AOP+ehCache簡單緩存系統解決方案

轉自:http://blog.csdn.net/liuzhenwen/archive/2009/03/12/3983952.aspx

需要使用Spring來實現一個Cache簡單的解決方案,具體需求如下:使用任意一個現有開源Cache Framework,要求可以Cache系統中Service或則DAO層的get/find等方法返回結果,如果數據更新(使用Create /update/delete方法),則刷新cache中相應的內容。

根據需求,計劃使用Spring AOP + ehCache來實現這個功能,採用ehCache原因之一是Spring提供了ehCache的支持,至於爲何僅僅支持ehCache而不支持 osCache和JBossCache無從得知(Hibernate???),但畢竟Spring提供了支持,可以減少一部分工作量:)。二是後來實現了 OSCache和JBoss Cache的方式後,經過簡單測試發現幾個Cache在效率上沒有太大的區別(不考慮集羣),決定採用ehCahce。

AOP嘛,少不了攔截器,先創建一個實現了MethodInterceptor接口的攔截器,用來攔截Service/DAO的方法調用,攔截到方法後,搜索該方法的結果在cache中是否存在,如果存在,返回cache中的緩存結果,如果不存在,返回查詢數據庫的結果,並將結果緩存到cache 中。

MethodCacheInterceptor.java

Java代碼
  1. package  com.co.cache.ehcache;  
  2.   
  3. import  java.io.Serializable;  
  4.   
  5. import  net.sf.ehcache.Cache;  
  6. import  net.sf.ehcache.Element;  
  7.   
  8. import  org.aopalliance.intercept.MethodInterceptor;  
  9. import  org.aopalliance.intercept.MethodInvocation;  
  10. import  org.apache.commons.logging.Log;  
  11. import  org.apache.commons.logging.LogFactory;  
  12. import  org.springframework.beans.factory.InitializingBean;  
  13. import  org.springframework.util.Assert;  
  14.   
  15. public   class  MethodCacheInterceptor  implements  MethodInterceptor, InitializingBean  
  16. {  
  17.     private   static   final  Log logger = LogFactory.getLog(MethodCacheInterceptor. class );  
  18.   
  19.     private  Cache cache;  
  20.   
  21.     public   void  setCache(Cache cache) {  
  22.         this .cache = cache;  
  23.     }  
  24.   
  25.     public  MethodCacheInterceptor() {  
  26.         super ();  
  27.     }  
  28.   
  29.     /**  
  30.      * 攔截Service/DAO的方法,並查找該結果是否存在,如果存在就返回cache中的值,  
  31.      * 否則,返回數據庫查詢結果,並將查詢結果放入cache  
  32.      */   
  33.     public  Object invoke(MethodInvocation invocation)  throws  Throwable {  
  34.         String targetName = invocation.getThis().getClass().getName();  
  35.         String methodName = invocation.getMethod().getName();  
  36.         Object[] arguments = invocation.getArguments();  
  37.         Object result;  
  38.       
  39.         logger.debug("Find object from cache is "  + cache.getName());  
  40.           
  41.         String cacheKey = getCacheKey(targetName, methodName, arguments);  
  42.         Element element = cache.get(cacheKey);  
  43.   
  44.         if  (element ==  null ) {  
  45.             logger.debug("Hold up method , Get method result and create cache........!" );  
  46.             result = invocation.proceed();  
  47.             element = new  Element(cacheKey, (Serializable) result);  
  48.             cache.put(element);  
  49.         }  
  50.         return  element.getValue();  
  51.     }  
  52.   
  53.     /**  
  54.      * 獲得cache key的方法,cache key是Cache中一個Element的唯一標識  
  55.      * cache key包括 包名+類名+方法名,如com.co.cache.service.UserServiceImpl.getAllUser  
  56.      */   
  57.     private  String getCacheKey(String targetName, String methodName, Object[] arguments) {  
  58.         StringBuffer sb = new  StringBuffer();  
  59.         sb.append(targetName).append("." ).append(methodName);  
  60.         if  ((arguments !=  null ) && (arguments.length !=  0 )) {  
  61.             for  ( int  i =  0 ; i < arguments.length; i++) {  
  62.                 sb.append("." ).append(arguments[i]);  
  63.             }  
  64.         }  
  65.         return  sb.toString();  
  66.     }  
  67.       
  68.     /**  
  69.      * implement InitializingBean,檢查cache是否爲空  
  70.      */   
  71.     public   void  afterPropertiesSet()  throws  Exception {  
  72.         Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it." );  
  73.     }  
  74.   
  75. }  



上面的代碼中可以看到,在方法public Object invoke(MethodInvocation invocation) 中,完成了搜索Cache/新建cache的功能。

Java代碼
  1. Element element = cache.get(cacheKey);  


這句代碼的作用是獲取cache中的element,如果cacheKey所對應的element不存在,將會返回一個null值

Java代碼
  1. result = invocation.proceed();  



這句代碼的作用是獲取所攔截方法的返回值,詳細請查閱AOP相關文檔。

隨後,再建立一個攔截器MethodCacheAfterAdvice,作用是在用戶進行create/update/delete操作時來刷新 /remove相關cache內容,這個攔截器實現了AfterReturningAdvice接口,將會在所攔截的方法執行後執行在public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3)方法中所預定的操作

Java代碼
  1. package  com.co.cache.ehcache;  
  2.   
  3. import  java.lang.reflect.Method;  
  4. import  java.util.List;  
  5.   
  6. import  net.sf.ehcache.Cache;  
  7.   
  8. import  org.apache.commons.logging.Log;  
  9. import  org.apache.commons.logging.LogFactory;  
  10. import  org.springframework.aop.AfterReturningAdvice;  
  11. import  org.springframework.beans.factory.InitializingBean;  
  12. import  org.springframework.util.Assert;  
  13.   
  14. public   class  MethodCacheAfterAdvice  implements  AfterReturningAdvice, InitializingBean  
  15. {  
  16.     private   static   final  Log logger = LogFactory.getLog(MethodCacheAfterAdvice. class );  
  17.   
  18.     private  Cache cache;  
  19.   
  20.     public   void  setCache(Cache cache) {  
  21.         this .cache = cache;  
  22.     }  
  23.   
  24.     public  MethodCacheAfterAdvice() {  
  25.         super ();  
  26.     }  
  27.   
  28.     public   void  afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3)  throws  Throwable {  
  29.         String className = arg3.getClass().getName();  
  30.         List list = cache.getKeys();  
  31.         for ( int  i =  0 ;i<list.size();i++){  
  32.             String cacheKey = String.valueOf(list.get(i));  
  33.             if (cacheKey.startsWith(className)){  
  34.                 cache.remove(cacheKey);  
  35.                 logger.debug("remove cache "  + cacheKey);  
  36.             }  
  37.         }  
  38.     }  
  39.   
  40.     public   void  afterPropertiesSet()  throws  Exception {  
  41.         Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it." );  
  42.     }  
  43.   
  44. }  


上面的代碼很簡單,實現了afterReturning方法實現自AfterReturningAdvice接口,方法中所定義的內容將會在目標方法執行後執行,在該方法中

Java代碼
  1. String className = arg3.getClass().getName();  

的作用是獲取目標class的全名,如:com.co.cache.test.TestServiceImpl,然後循環cache的key list,remove cache中所有和該class相關的element。

隨後,開始配置ehCache的屬性,ehCache需要一個xml文件來設置ehCache相關的一些屬性,如最大緩存數量、cache刷新的時間等等.
ehcache.xml

Java代碼
  1. <ehcache>  
  2.     <diskStore path="c:\\myapp\\cache" />  
  3.     <defaultCache  
  4.         maxElementsInMemory="1000"   
  5.         eternal="false"   
  6.         timeToIdleSeconds="120"   
  7.         timeToLiveSeconds="120"   
  8.         overflowToDisk="true"   
  9.         />  
  10.   <cache name="DEFAULT_CACHE"   
  11.         maxElementsInMemory="10000"   
  12.         eternal="false"   
  13.         timeToIdleSeconds="300000"   
  14.         timeToLiveSeconds="600000"   
  15.         overflowToDisk="true"   
  16.         />  
  17. </ehcache>  


配置每一項的詳細作用不再詳細解釋,有興趣的請google下 ,這裏需要注意一點defaultCache標籤定義了一個默認的Cache,這個Cache是不能刪除的,否則會拋出No default cache is configured異常。另外,由於使用攔截器來刷新Cache內容,因此在定義cache生命週期時可以定義較大的數值,timeToIdleSeconds="300000" timeToLiveSeconds="600000",好像還不夠大?

然後,在將Cache和兩個攔截器配置到Spring,這裏沒有使用2.0裏面AOP的標籤。
cacheContext.xml

Java代碼
  1. <?xml version= "1.0"  encoding= "UTF-8" ?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"   "http://www.springframework.org/dtd/spring-beans.dtd" >  
  3. <beans>  
  4.     <!-- 引用ehCache的配置 -->  
  5.     <bean id="defaultCacheManager"   class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean" >  
  6.       <property name="configLocation" >  
  7.         <value>ehcache.xml</value>  
  8.       </property>  
  9.     </bean>  
  10.       
  11.     <!-- 定義ehCache的工廠,並設置所使用的Cache name -->  
  12.     <bean id="ehCache"   class = "org.springframework.cache.ehcache.EhCacheFactoryBean" >  
  13.       <property name="cacheManager" >  
  14.         <ref local="defaultCacheManager" />  
  15.       </property>  
  16.       <property name="cacheName" >  
  17.           <value>DEFAULT_CACHE</value>  
  18.       </property>  
  19.     </bean>  
  20.   
  21.     <!-- find/create cache攔截器 -->  
  22.     <bean id="methodCacheInterceptor"   class = "com.co.cache.ehcache.MethodCacheInterceptor" >  
  23.       <property name="cache" >  
  24.         <ref local="ehCache"  />  
  25.       </property>  
  26.     </bean>  
  27.     <!-- flush cache攔截器 -->  
  28.     <bean id="methodCacheAfterAdvice"   class = "com.co.cache.ehcache.MethodCacheAfterAdvice" >  
  29.       <property name="cache" >  
  30.         <ref local="ehCache"  />  
  31.       </property>  
  32.     </bean>  
  33.       
  34.     <bean id="methodCachePointCut"   class = "org.springframework.aop.support.RegexpMethodPointcutAdvisor" >  
  35.       <property name="advice" >  
  36.         <ref local="methodCacheInterceptor" />  
  37.       </property>  
  38.       <property name="patterns" >  
  39.         <list>  
  40.             <value>.*find.*</value>  
  41.             <value>.*get.*</value>  
  42.         </list>  
  43.       </property>  
  44.     </bean>  
  45.     <bean id="methodCachePointCutAdvice"   class = "org.springframework.aop.support.RegexpMethodPointcutAdvisor" >  
  46.       <property name="advice" >  
  47.         <ref local="methodCacheAfterAdvice" />  
  48.       </property>  
  49.       <property name="patterns" >  
  50.         <list>  
  51.           <value>.*create.*</value>  
  52.           <value>.*update.*</value>  
  53.           <value>.*delete.*</value>  
  54.         </list>  
  55.       </property>  
  56.     </bean>  
  57. </beans>  


上面的代碼最終創建了兩個"切入點",methodCachePointCut和methodCachePointCutAdvice,分別用於攔截不同方法名的方法,可以根據需要任意增加所需要攔截方法的名稱。
需要注意的是

Java代碼
  1. <bean id= "ehCache"   class = "org.springframework.cache.ehcache.EhCacheFactoryBean" >  
  2.       <property name="cacheManager" >  
  3.         <ref local="defaultCacheManager" />  
  4.       </property>  
  5.       <property name="cacheName" >  
  6.           <value>DEFAULT_CACHE</value>  
  7.       </property>  
  8.     </bean>  


如果cacheName屬性內設置的name在ehCache.xml中無法找到,那麼將使用默認的cache(defaultCache標籤定義).

事實上到了這裏,一個簡單的Spring + ehCache Framework基本完成了,爲了測試效果,舉一個實際應用的例子,定義一個TestService和它的實現類TestServiceImpl,裏面包含

兩個方法getAllObject()和updateObject(Object Object),具體代碼如下
TestService.java

Java代碼
  1. package  com.co.cache.test;  
  2.   
  3. import  java.util.List;  
  4.   
  5. public   interface  TestService {  
  6.     public  List getAllObject();  
  7.   
  8.     public   void  updateObject(Object Object);  
  9. }  



TestServiceImpl.java

Java代碼
  1. package  com.co.cache.test;  
  2.   
  3. import  java.util.List;  
  4.   
  5. public   class  TestServiceImpl  implements  TestService  
  6. {  
  7.     public  List getAllObject() {  
  8.         System.out.println("---TestService:Cache內不存在該element,查找並放入Cache!" );  
  9.         return   null ;  
  10.     }  
  11.   
  12.     public   void  updateObject(Object Object) {  
  13.         System.out.println("---TestService:更新了對象,這個Class產生的cache都將被remove!" );  
  14.     }  
  15. }  


使用Spring提供的AOP進行配置
applicationContext.xml

Java代碼
  1. <?xml version= "1.0"  encoding= "UTF-8" ?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"   "http://www.springframework.org/dtd/spring-beans.dtd" >  
  3.   
  4. <beans>  
  5.     <import  resource= "cacheContext.xml" />  
  6.       
  7.     <bean id="testServiceTarget"   class = "com.co.cache.test.TestServiceImpl" />  
  8.       
  9.     <bean id="testService"   class = "org.springframework.aop.framework.ProxyFactoryBean" >  
  10.       <property name="target" >  
  11.           <ref local="testServiceTarget" />  
  12.       </property>  
  13.       <property name="interceptorNames" >  
  14.         <list>  
  15.           <value>methodCachePointCut</value>  
  16.           <value>methodCachePointCutAdvice</value>  
  17.         </list>  
  18.       </property>  
  19.     </bean>  
  20. </beans>  


這裏一定不能忘記import cacheContext.xml文件,不然定義的兩個攔截器就沒辦法使用了。

最後,寫一個測試的代碼
MainTest.java

Java代碼
  1. package  com.co.cache.test;  
  2.   
  3. import  org.springframework.context.ApplicationContext;  
  4. import  org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public   class  MainTest{  
  7.     public   static   void  main(String args[]){  
  8.         String DEFAULT_CONTEXT_FILE = "/applicationContext.xml" ;  
  9.         ApplicationContext context =  new  ClassPathXmlApplicationContext(DEFAULT_CONTEXT_FILE);  
  10.         TestService testService = (TestService)context.getBean("testService" );  
  11.   
  12.         System.out.println("1--第一次查找並創建cache" );  
  13.         testService.getAllObject();  
  14.           
  15.         System.out.println("2--在cache中查找" );  
  16.         testService.getAllObject();  
  17.           
  18.         System.out.println("3--remove cache" );  
  19.         testService.updateObject(null );  
  20.           
  21.         System.out.println("4--需要重新查找並創建cache" );  
  22.         testService.getAllObject();  
  23.     }     
  24. }  



運行,結果如下

Java代碼
  1. 1 --第一次查找並創建cache  
  2. ---TestService:Cache內不存在該element,查找並放入Cache!  
  3. 2 --在cache中查找  
  4. 3 --remove cache  
  5. ---TestService:更新了對象,這個Class產生的cache都將被remove!  
  6. 4 --需要重新查找並創建cache  
  7. ---TestService:Cache內不存在該element,查找並放入Cache!  



大功告成 .可以看到,第一步執行getAllObject(),執行TestServiceImpl內的方法,並創建了cache,在第二次執行 getAllObject()方法時,由於cache有該方法的緩存,直接從cache中get出方法的結果,所以沒有打印出 TestServiceImpl中的內容,而第三步,調用了updateObject方法,和TestServiceImpl相關的cache被 remove,所以在第四步執行時,又執行TestServiceImpl中的方法,創建Cache。

網上也有不少類似的例子,但是很多都不是很完備,自己參考了一些例子的代碼,其實在spring-modules中也提供了對幾種cache的支持,ehCache,OSCache,JBossCache這些,看了一下,基本上都是採用類似的方式,只不過封裝的更完善一些,主要思路也還是 Spring的AOP,有興趣的可以研究一下。

 

hibernate緩存

1.在applicationContext.xml中引入

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="configLocation" value="${hibernate.config.location}" />
		<property name="mappingLocations">
			<list>
				<value>classpath:/com/mysougou/mtmibp/center/core/entity/*.hbm.xml</value>
				<value>classpath:/com/mysougou/mtmibp/cms/cms/entity/*.hbm.xml</value>
				<value>classpath:/com/mysougou/mtmibp/cms/article/entity/*.hbm.xml</value>
				<value>classpath:/com/mysougou/mtmibp/cms/download/entity/*.hbm.xml</value>
				<value>classpath:/com/mysougou/mtmibp/cms/auxiliary/entity/*.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<!--hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect-->
			<!--hibernate.dialect=org.hibernate.dialect.SQLServerDialect-->
			<value>
			hibernate.dialect=org.hibernate.dialect.SQLServerDialect
			hibernate.show_sql=true
			hibernate.format_sql=false
			hibernate.query.substitutions=true 1, false 0
			hibernate.jdbc.batch_size=20
			hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
			hibernate.cache.provider_configuration_file_resource_path=/ehcache-hibernate.xml
			</value>
		</property>
		<property name="entityInterceptor">   
			<ref local="treeInterceptor"/>
		</property>
	</bean>
ehcache-hibernate.xml

 

<?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="java.io.tmpdir/mysougou2/hibernate"/>


	<cacheManagerEventListenerFactory class="" properties=""/>


    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>


	<cache name="com.mysougou.mtmibp.core.entity.Website" maxElementsInMemory="100" eternal="true" overflowToDisk="true"/>


	<cache name="com.mysougou.mtmibp.core.entity.Global" maxElementsInMemory="1" eternal="true" overflowToDisk="true"/>


	<cache name="com.mysougou.mtmibp.core.entity.Function" maxElementsInMemory="3000" eternal="true" overflowToDisk="true"/>


	<cache name="com.mysougou.mtmibp.core.entity.Function.child" maxElementsInMemory="3000" eternal="true" overflowToDisk="true"/>


</ehcache>

 

發佈了71 篇原創文章 · 獲贊 0 · 訪問量 2506
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章