Ehcache有兩種使用方式,一種通過在代碼中直接調用Ehcahe提供的接口進行緩存,另一種就是通過與Spring結合,通過對方法的攔截技術來緩存方法調用返回的結果.
方式一:手動配置你的EHCACHE
ehcache.xml中加入如下節點,並按需設置參數.
<cache name="your cache name"
maxElementsInMemory="300"
eternal="false"
timeToIdleSeconds="500"
timeToLiveSeconds="500"
overflowToDisk="true"
/>
參數的含義:
maxInMemory - 設定內存中創建對象的最大值。
eternal - 設置元素(譯註:內存中對象)是否永久駐留。如果是,將忽略超
時限制且元素永不消亡。
timeToIdleSeconds - 設置某個元素消亡前的停頓時間。
也就是在一個元素消亡之前,兩次訪問時間的最大時間間隔值。
這只能在元素不是永久駐留時有效(譯註:如果對象永恆不滅,則
設置該屬性也無用)。
如果該值是 0 就意味着元素可以停頓無窮長的時間。
timeToLiveSeconds - 爲元素設置消亡前的生存時間。
也就是一個元素從構建到消亡的最大時間間隔值。
這只能在元素不是永久駐留時有效。
overflowToDisk - 設置當內存中緩存達到 maxInMemory 限制時元素是否可寫到磁盤
上。
通過寫代碼調用Ehcache的接口。
優點:
1. 可以在任何java代碼中使用來緩存需要的結果
2. 可以緩存非系列化的java對象
缺點:
1. 緩存代碼直接嵌入應用代碼中,無法分離
綜上所述,當需要在一個方法內部使用緩存或緩存非系列化對象時,選用此緩存方式。
示例代碼:
Vector vobject= new Vector(); Cache cache = CacheManager.getInstance().getCache("your cache name"); String key = "someKeyOfTheCacheElement";Element element = cache.get(key); if (element == null) { vobject= loadObjDAO(arg1, arg2);
cache.put(new Element(key, vobject));} else { vobject= (Vector) element.getValue();}
方式二:通過與spring結合,可以對bean中的任意一個方法返回的結果進行緩存。
優點:
1. 不需要寫任何緩存代碼,緩存代碼與應用代碼分離,通過配置方式對方法返回結果進行緩存
缺點:
1. 只能以方法爲單位,對方法返回結果緩存
2. 暫時不能緩存非序列化對象
如果想對某個bean的所有方法進行緩存,可以在你的spring配置文件中加入如下代碼:
<bean id="cacheBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="yourcompany.youBean"/>
</property>
<property name="interceptorNames">
<list>
<value>methodCacheInterceptor</value>
</list>
</property>
</bean>
注:methodCacheInterceptor攔截器實現了org.aopalliance.intercept.MethodInterceptor接口。一旦運行起來,它首先檢查被攔截方法是否被配置爲可緩存的。這將可選擇性的配置想要緩存的 bean 方法,只要調用的方法配置爲可緩存,攔截器將爲該方法生成 cache key 並檢查該方法返回的結果是否已緩存。如果已緩存,就返回緩存的結果,否則再次調用被攔截方法,並緩存結果供下次調用。
如果想對bean中的一部分方法進行緩存,如對TestCacheBean所有get方法進行緩存,需要在你的spring配置文件中加入如下代碼:
<bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref bean="methodCacheInterceptor"/>
</property>
<property name="patterns">
<list>
<value>>*.get*</value>
</list>
</property>
</bean>
<bean id="cacheBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="com.yourcompany.TestCacheBean"/>
</property>
<property name="interceptorNames">
<list>
<value>methodCacheInterceptor</value>
</list>
</property>
</bean>
安裝與資料:
如果想單獨安裝Ehcache ,需把ehcache-X.X.jar 和相關類庫方到classpath中。如果你的項目已安裝了Hibernate2.1 ,則不需要做什麼,直接可以使用Ehcache
1. Ehcache官方網站:http://ehcache.sourceforge.net/samples.html