引用:http://www.javaeye.com/topic/99721
需要使用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
package com.co.cache.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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean
{
private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);
private Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public MethodCacheInterceptor() {
super();
}
/**
* 攔截Service/DAO的方法,並尋找該結果是否存在,如果存在就返回cache中的值,
* 否則,返回資料庫查詢結果,並將查詢結果放入cache
*/
public Object invoke(MethodInvocation invocation) throws Throwable {
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
Object[] arguments = invocation.getArguments();
Object result;
logger.debug("Find object from cache is " + cache.getName());
String cacheKey = getCacheKey(targetName, methodName, arguments);
Element element = cache.get(cacheKey);
if (element == null) {
logger.debug("Hold up method , Get method result and create cache........!");
result = invocation.proceed();
element = new Element(cacheKey, (Serializable) result);
cache.put(element);
}
return element.getValue();
}
/**
* 獲得cache key的方法,cache key是Cache中一個Element的唯一標識
* cache key包括 包名+類名+方法名,如com.co.cache.service.UserServiceImpl.getAllUser
*/
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是否為空白
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");
}
}
上面的代碼中可以看到,在方法public Object invoke(MethodInvocation invocation) 中,完成了搜尋Cache/建立cache的功能。
Element element = cache.get(cacheKey);
這句代碼的作用是擷取cache中的element,如果cacheKey所對應的element不存在,將會返回一個null值
result = invocation.proceed();
這句代碼的作用是擷取所攔截方法的傳回值,詳細請查閱AOP相關文檔。
隨後,再建立一個攔截器MethodCacheAfterAdvice,作用是在使用者進行create/update/delete操作時來重新整理 /remove相關cache內容,這個攔截器實現了AfterReturningAdvice介面,將會在所攔截的方法執行後執行在public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3)方法中所預定的操作
package com.co.cache.ehcache;
import java.lang.reflect.Method;
import java.util.List;
import net.sf.ehcache.Cache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class MethodCacheAfterAdvice implements AfterReturningAdvice, InitializingBean
{
private static final Log logger = LogFactory.getLog(MethodCacheAfterAdvice.class);
private Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public MethodCacheAfterAdvice() {
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);
logger.debug("remove cache " + cacheKey);
}
}
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");
}
}
上面的代碼很簡單,實現了afterReturning方法實現自AfterReturningAdvice介面,方法中所定義的內容將會在目標方法執行後執行,在該方法中
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
<ehcache>
<diskStore path="c://myapp//cache"/>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="DEFAULT_CACHE"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300000"
timeToLiveSeconds="600000"
overflowToDisk="true"
/>
</ehcache>
配置每一項的詳細作用不再詳細解釋,有興趣的請google下 ,這裡需要注意一點defaultCache標籤定義了一個預設的Cache,這個Cache是不能刪除的,否則會拋出No default cache is configured異常。另外,由於使用攔截器來重新整理Cache內容,因此在定義cache生命週期時可以定義較大的數 值,timeToIdleSeconds="300000" timeToLiveSeconds="600000",好像還不夠大。
然後,在將Cache和兩個攔截器配置到Spring,這裡沒有使用2.0裡面AOP的標籤。
cacheContext.xml
<?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的工廠,並設定所使用的Cache name -->
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="defaultCacheManager"/>
</property>
<property name="cacheName">
<value>DEFAULT_CACHE</value>
</property>
</bean>
<!-- find/create cache攔截器 -->
<bean id="methodCacheInterceptor" class="com.co.cache.ehcache.MethodCacheInterceptor">
<property name="cache">
<ref local="ehCache" />
</property>
</bean>
<!-- flush cache攔截器 -->
<bean id="methodCacheAfterAdvice" class="com.co.cache.ehcache.MethodCacheAfterAdvice">
<property name="cache">
<ref local="ehCache" />
</property>
</bean>
<bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="methodCacheInterceptor"/>
</property>
<property name="patterns">
<list>
<value>.*find.*</value>
<value>.*get.*</value>
</list>
</property>
</bean>
<bean id="methodCachePointCutAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="methodCacheAfterAdvice"/>
</property>
<property name="patterns">
<list>
<value>.*create.*</value>
<value>.*update.*</value>
<value>.*delete.*</value>
</list>
</property>
</bean>
</beans>
上面的代碼最終建立了兩個"切入點",methodCachePointCut和methodCachePointCutAdvice,分別用於攔截不同方法名的方法,可以根據需要任意增加所需要攔截方法的名稱。
需要注意的是
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="defaultCacheManager"/>
</property>
<property name="cacheName">
<value>DEFAULT_CACHE</value>
</property>
</bean>
如果cacheName屬性內設定的name在ehCache.xml中無法找到,那麼將使用預設的cache(defaultCache標籤定義).
事實上到了這裡,一個簡單的Spring + ehCache Framework基本完成了,為了測試效果,舉一個實際應用的例子,定義一個TestService和它的實作類別TestServiceImpl,裡麵包含
兩個方法getAllObject()和updateObject(Object Object),具體代碼如下
TestService.java
package com.co.cache.test;
import java.util.List;
public interface TestService {
public List getAllObject();
public void updateObject(Object Object);
}
TestServiceImpl.java
package com.co.cache.test;
import java.util.List;
public class TestServiceImpl implements TestService
{
public List getAllObject() {
System.out.println("---TestService:Cache內不存在該element,尋找並放入Cache。");
return null;
}
public void updateObject(Object Object) {
System.out.println("---TestService:更新了對象,這個Class產生的cache都將被remove。");
}
}
使用Spring提供的AOP進行配置
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<import resource="cacheContext.xml"/>
<bean id="testServiceTarget" class="com.co.cache.test.TestServiceImpl"/>
<bean id="testService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref local="testServiceTarget"/>
</property>
<property name="interceptorNames">
<list>
<value>methodCachePointCut</value>
<value>methodCachePointCutAdvice</value>
</list>
</property>
</bean>
</beans>
這裡一定不能忘記import cacheContext.xml檔案,不然定義的兩個攔截器就沒辦法使用了。
最後,寫一個測試的代碼
MainTest.java
package com.co.cache.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest{
public static void main(String args[]){
String DEFAULT_CONTEXT_FILE = "/applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(DEFAULT_CONTEXT_FILE);
TestService testService = (TestService)context.getBean("testService");
System.out.println("1--第一次尋找並建立cache");
testService.getAllObject();
System.out.println("2--在cache中尋找");
testService.getAllObject();
System.out.println("3--remove cache");
testService.updateObject(null);
System.out.println("4--需要重新尋找並建立cache");
testService.getAllObject();
}
}
運行,結果如下
1--第一次尋找並建立cache
---TestService:Cache內不存在該element,尋找並放入Cache。
2--在cache中尋找
3--remove cache
---TestService:更新了對象,這個Class產生的cache都將被remove。
4--需要重新尋找並建立cache
---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,有興趣的可以研究一下。