spring+ehcache實戰--效能優化之道
在做系統整合平臺專案的時候遇到了一個比較麻煩的問題,原因是使用考試系統的時候所依賴的是基礎系統釋出的webservice來獲取基礎資料,webservice的跨網路傳輸本身或多或少會對系統性能產生一定影響再加上傳輸的資料量比較大這樣對系統性能的影響就更大了,但是導致系統性能下降的另外一個原因就是頻繁的開啟關閉資料庫。針對這兩個問題我們採取了兩個解決方案以期將效能影響降至最低第一就是webservice由原先的傳輸序列化物件改為傳輸json串,第二個就是針對資料庫連線的開閉問題作了快取處理。本文我們主要探討第二個解決方案ehcache。
ehcache是一個非常不錯的快取框架,配置前來簡單並且功能強大,在專案中加快取的地方主要有兩處,第一是快取實體物件,這層快取加在實體層,主要使用的是hibernate的二級快取(同時一定要開啟查詢快取)利用spring的AOP註解即可簡單搞定,而在其他查詢方法上主要用的就是ehcache,用來快取方法返回的各種物件。開啟hibernate的查詢快取和二級快取比較簡單,在此不做過多介紹,我們主要來看ehcache的用法。
1.首先我們用到的是Interceptor,定義兩個攔截器MethodCacheInterceptor和MethodCacheAfterAdvice,前者主要用來攔截以get和find開頭的方法(用於快取結果),而第二個攔截器主要用來攔截以update開頭的方法,用來清除快取,下面讓我們來看一下具體的程式碼:
第二個攔截器的程式碼如下: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 中的值, 31 * * 否則,返回資料庫查詢結果,並將查詢結果放入cache 32 */ 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); System.out.println("-----非快取中查詢,查詢後放入快取"); cache.put(element); }else{ System.out.println("----快取中查詢----"); } return element.getValue(); } /** * 獲得cache key 的方法,cache key 是Cache 中一個Element 的唯一標識 55 * cache key * 包括包名+類名+方法名,如 com.co.cache.service.UserServiceImpl.getAllUser 56 */ 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."); } }
有了這兩個攔截器,接下來我們所要做的就是為將這兩個攔截器引入進專案讓其發揮作用,這些配置都在ehcache.xml檔案中進行,下面來看該檔案的具體配置: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); System.out.println("------清除快取----"); logger.debug("remove cache " + cacheKey); } } } public void afterPropertiesSet() throws Exception { Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it."); } }
<?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>
這樣就將攔截器的配置以及快取配置引入導了專案中,快取配置資訊主要放在ehcache.xml檔案中,詳細資訊如下:
<ehcache>
<diskStore path="H:\\temp\\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>
至此我們的相應配置都已經做好了,下面讓我們建立測試類來測試快取是否起作用,在這裡我們主要用的類有三個,來看具體程式碼:
public interface TestService {
public List getAllObject();
public void updateObject(Object Object);
}
TestService是呼叫介面,而下面的TestServiceImpl是其實現,程式碼如下:
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!");
}
}
下面的JunitTestClass為真正的測試類,程式碼如下:
public class JunitTestClass {
@Test
public void testRun(){
String DEFAULT_CONTEXT_FILE = "/applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(
DEFAULT_CONTEXT_FILE);
TestService testService = (TestService) context.getBean("testService");
//第一次查詢
testService.getAllObject();
//第二次查詢
testService.getAllObject();
//執行update方法(應該清除快取)
testService.updateObject(null);
//第三次查詢
testService.getAllObject();
}
}
分析測試程式碼,當第一次執行getAllObject()方法的時候由於是第一次執行查詢操作,會被MethodCacheInterceptor攔截,當MethodCacheInterceptor發現沒有命中快取的時候,執行invoke()方法,讓程式去資料庫查詢(本程式中只是模擬了對資料庫的查詢,並沒有真正查詢資料庫,不過其所表達的意思是與查詢資料庫沒有區別的),我們看到這是會執行TestServiceImpl的getAllObject()方法,打印出一條語句同時列印攔截器中的“-----非快取中查詢,查詢後放入快取”語句,當第二次執行該方法的時候由於已經存在了快取,所以不再執行TestServiceImpl的getAllObject()方法,同時只打印攔截器中的“----快取中查詢----”語句,當執行updateObject()方法的時候會被MethodCacheAfterAdvice攔截,並執行TestServiceImpl的updateObject()方法,所以會列印“---TestService:更新了物件,這個Class 產生的cache 都將被remove”語句以及攔截器中的“------刪除快取----”語句,當執行第三次查詢的時候,由於快取已經被清除,所以會在此輸出和第一次一樣的語句,下面來驗證一下我們的推測是否正確:
輸出結果與我們猜測的一樣,也就是說此時ehcache快取在程式中已經起作用了。