本文章摘編、轉載需要註明來源 http://write.blog.csdn.net/postedit/8599512
緩衝熱點資料是提高訪問效率的重要手段之一,下面我用encache示範下如何做service層的資料緩衝
先寫個方法攔截器,當然要先繼承MethodInterceptor,encache的標識key我是將參數序列成json字元
可能強制部分會影響效能,建議判斷null後再一次判斷cache.get(key)是否為null,同步的第一人的操作已經執行完畢,那element裡面就不為null,這樣其他的並發使用者就不需要
繼續再執行put值的操作,這樣做應該能比較好地降低synchronized帶來的負面影響
/** * 緩衝方法攔截器核心代碼 * * @author shadow * @email 124010356@qq.com * @create 2012.04.28 */public class EhCacheMethodInterceptor implements MethodInterceptor,InitializingBean { // private static final Logger log = Logger.getLogger(MethodCacheInterceptor.class);private Cache cache;public EhCacheMethodInterceptor() {super();}public void setCache(Cache cache) {this.cache = cache;}public void afterPropertiesSet() throws Exception {// /log.info(cache A cache is required. Use setCache(Cache) to provide one.");}public Object invoke(MethodInvocation invocation) throws Throwable {String targetName = invocation.getThis().getClass().getName();String methodName = invocation.getMethod().getName();Object[] arguments = invocation.getArguments();String cacheKey = getCacheKey(targetName, methodName, arguments);Element element = cache.get(cacheKey);// 緩衝節點不存在的情況if (null == element) {synchronized (this) {// 這裡判斷是為了降低強制同步的負面影響,只需第一個操作該添加過程,後來者則跳過if (null == cache.get(cacheKey))element = putValueToCache(invocation, element, cacheKey);}}// 返回緩衝值return element.getValue();}// 新增節點放到緩衝區private Element putValueToCache(MethodInvocation invocation,Element element, String cacheKey) throws Throwable {Object result = invocation.proceed();element = new Element(cacheKey, (Serializable) result);cache.put(element);return element;}/** * * 返回具體的方法(全路徑+方法名+參數值) * * @param targetName * 全路徑 * @param methodName * 方法名稱 * @param arguments * 參數(轉換成JSON格式方便比較) * @return String */private String getCacheKey(String targetName, String methodName,Object[] arguments) {StringBuffer buffer = new StringBuffer("");buffer.append(targetName).append(".").append(methodName);for (Object argument : arguments) {buffer.append(".").append(BaseSupport.ContextUtil.getJSON(argument));}return buffer.toString();}}
再做個同步資料的限制類,當我們執行remove等那些方法的時候會清空encache裡面的相關緩衝的方法資料,下次再訪問的時候會重新在資料庫裡讀取更新後的資料,到這裡基本就可以了
package com.shadow.extras.cache;import java.util.List;import net.sf.ehcache.Cache;import net.sf.ehcache.CacheManager;import org.apache.log4j.Logger;import org.aspectj.lang.JoinPoint;/** * 快取資料變動後讓資料保持同步狀態 * * @author shadow * @email 124010356@qq.com * @create 2012.04.28 */public class EhCacheMethodAfterAdvice {protected final Logger logger = Logger.getLogger(getClass());private CacheManager cacheManager;private Cache cacheName;/** * 未經處理資料發生變更時保持強一致性(刪除緩存管理器裡指定key的value) * * @param joinPoint */public void afterReturning(JoinPoint joinPoint) {// String methodName = joinPoint.getSignature().getName();// 得到執行的方法if (cacheManager != null && cacheName != null) {// 擷取緩衝堆Class<?> clazz = joinPoint.getTarget().getClass();List<?> list = cacheName.getKeys();for (int i = 0, len = list.size(); i < len; i++) {String key = String.valueOf(list.get(i));if (key.startsWith(clazz.getName()))cacheName.remove(key);}} else {if (cacheManager == null)logger.error("緩衝管理器不存在!");if (cacheName == null)logger.error("緩衝堆不存在!");}}public CacheManager getCacheManager() {return cacheManager;}public void setCacheManager(CacheManager cacheManager) {this.cacheManager = cacheManager;}public Cache getCacheName() {return cacheName;}public void setCacheName(Cache cacheName) {this.cacheName = cacheName;}}
然後是在xml裡配置需要攔截的方法
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:context="http://www.springframework.org/schema/context"xmlns:ehcache="http://www.springframework.org/schema/ehcache"xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/ehcache http://www.springframework.org/schema/cache/springmodules-ehcache.xsd"><!-- 配置緩衝管理器 --><bean id="defaultCacheManager"class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"><property name="configLocation"><value>classpath:ehcache.xml</value></property></bean><!-- 配置一個簡單的緩衝工廠bean對象 --><bean id="defaultCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"><property name="cacheManager"><ref local="defaultCacheManager" /></property><!-- 使用緩衝 關聯ehcache.xml中的緩衝配置 --><property name="cacheName" value="defaultCache" /></bean><!-- 配置一個簡單的緩衝工廠bean對象 --><bean id="commonCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"><property name="cacheManager"><ref local="defaultCacheManager" /></property><!-- 使用緩衝 關聯ehcache.xml中的緩衝配置 --><property name="cacheName" value="commonCache" /></bean><!-- 配置一個緩衝攔截器對象,處理具體的緩衝業務 --><bean id="ehCacheMethodInterceptor" class="com.shadow.extras.cache.EhCacheMethodInterceptor"><property name="cache" ref="defaultCache" /></bean><!-- 參與緩衝的切入點對象 (切入點對象,確定何時何地調用攔截器) --><bean id="methodCachePointCut"class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"><!-- 配置緩衝切面 --><property name="advice" ref="ehCacheMethodInterceptor" /><!--配置哪些方法參與緩衝策略 .表示符合任何單一字元 ### +表示符合前一個字元一次或多次 ### *表示符合前一個字元零次或多次 ###\Escape任何Regular expression使用到的符號--><!-- .*表示前面的首碼(包括包名) 表示print方法--><property name="patterns"><list><value>com.xshadow.mvc.service\..*Service.*\.find.*</value></list></property></bean><!-- 配置一個緩衝攔截器對象,處理具體的同步緩衝業務 --><bean id="ehCacheMethodAfterAdvice" class="com.shadow.extras.cache.EhCacheMethodAfterAdvice"><property name="cacheManager" ref="defaultCacheManager" /><property name="cacheName" ref="defaultCache" /></bean><aop:config><aop:aspect id="methodCachePointCutAdviceAspect" ref="ehCacheMethodAfterAdvice"><aop:after method="afterReturning"pointcut="execution(* com.shadow.mvc.service.*Service.modify*(..))" /><aop:after method="afterReturning"pointcut="execution(* com.shadow.mvc.service.*Service.save*(..))" /><aop:after method="afterReturning"pointcut="execution(* com.shadow.mvc.service.*Service.remove*(..))" /></aop:aspect></aop:config></beans>
以後我們配置需要緩衝的地方就直接在檔案裡配置就可以了,至於分布式的緩衝應用有空再寫