導言<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
從 Spring 1.1.1 開始,EHCache 就作爲一種通用緩存解決方案集成進 Spring。
我將示範攔截器的例子,它能把方法返回的結果緩存起來。
利用 Spring IoC 配置 EHCache
在 Spring 裏配置 EHCache 很簡單。你只需一個 ehcache.xml 文件,該文件用於配置 EHCache:
<ehcache> <!—設置緩存文件 .data 的創建路徑。 如果該路徑是 Java 系統參數,當前虛擬機會重新賦值。 下面的參數這樣解釋:
下列屬性是 defaultCache 必須的: maxInMemory - 設定內存中創建對象的最大值。 <cache name="org.taha.cache.METHOD_CACHE" |
攔截器將使用 ”org.taha.cache.METHOD_CACHE” 區域緩存方法返回結果。下面利用 Spring IoC 讓 bean 來訪問這一區域。
<!-- ====================== 緩存 ======================= --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> |
構建我們的 MethodCacheInterceptor
該攔截器實現org.aopalliance.intercept.MethodInterceptor接口。一旦運行起來(kicks-in),它首先檢查被攔截方法是否被配置爲可緩存的。這將可選擇性的配置想要緩存的 bean 方法。只要調用的方法配置爲可緩存,攔截器將爲該方法生成 cache key 並檢查該方法返回的結果是否已緩存。如果已緩存,就返回緩存的結果,否則再次調用被攔截方法,並緩存結果供下次調用。
org.taha.interceptor.MethodCacheInterceptor
/* package org.taha.interceptor; import java.io.Serializable; import org.aopalliance.intercept.MethodInterceptor; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import net.sf.ehcache.Cache; /** private Cache cache; /** /** /** logger.debug("looking for method result in cache"); //cache method result /** return sb.toString(); |
MethodCacheInterceptor 代碼說明了:
- 默認條件下,所有方法返回結果都被緩存了(methodNames 是 null)
- 緩存區利用 IoC 形成
- cacheKey 的生成還包括方法參數的因素(譯註:參數的改變會影響 cacheKey)
使用 MethodCacheInterceptor
下面摘錄了怎樣配置 MethodCacheInterceptor:
<bean id="methodCacheInterceptor" class="org.taha.interceptor.MethodCacheInterceptor"> <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <bean id="myBean" class="org.springframework.aop.framework.ProxyFactoryBean"> |
譯註
夏昕所著《Hibernate 開發指南》,其中他這樣描述 EHCache 配置文件的:
<ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" //Cache中最大允許保存的數據數量 eternal="false" //Cache中數據是否爲常量 timeToIdleSeconds="120" //緩存數據鈍化時間 timeToLiveSeconds="120" //緩存數據的生存時間 overflowToDisk="true" //內存不足時,是否啓用磁盤緩存 /> </ehcache> |
(請注意!引用、轉貼本文應註明原作者:Rosen Jiang 以及出處:http://blog.csdn.net/rosen)