利用Spring AOP 更新Memcached 緩存策略的實現

對於網上關於memcached緩存更新策略 數不勝數,但是沒有一遍完整的,看起來都很費勁,由於項目中用到的memcache,自然就想到了memcache緩存更新策略的實現。

你可以把你更新緩存的代碼嵌套你的代碼中,但是這樣很不好,混換了你service的代碼,要是以後再換別的緩存產品,那麼你還要每個類去找,去修改很是麻煩。由於之前是這樣寫的,很是痛苦,所以這次要用spring aop來實現。

在做本次試驗之前 ,首先要準備好memcache,具體安裝步驟請參考:http://www.linuxidc.com/Linux/2012-03/56500.htm

瞭解memcache,請參考:對memcached使用的總結和使用場景  http://www.linuxidc.com/Linux/2012-03/56501.htm

下面說以下具體更新策略的實現思路:

首先我們會定義兩個註解類,來說明是插入(Cache)緩存還是刪除(Flush)緩存,這兩個類可以方法上,來對你service需要進行緩存方法操作進行註解標記,註解類內用key的前綴,和緩存的有效時間,接着spring aop 攔截service層含有這個兩個註解的方法,獲得key的前綴+方法明+參數組裝成key值,存入到一張臨時表內,如果是Cache註解的話,先判斷,緩衝中有沒,有從緩存中取得,沒有從數據庫中查詢,然後存緩存,返回結果。如果是Flush註解,說明是刪除緩存,那麼首先獲得註解中key值的前綴,查詢庫中所以以這個爲前綴的key,查詢出來 ,刪除數據庫中的數據,最後在刪除緩存中所有的符合這些key的緩存,來達到更新緩存。另外這張臨時表,可以做個定時任務日終的時候 ,刪除一些無用的數據。

具體代碼:

 Cache註解

  1. package com.woaika.loan.commons.annotation;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Inherited;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.RetentionPolicy;  
  8. import java.lang.annotation.Target;  
  9.   
  10. /** 
  11.  * 用於在查詢的時候 ,放置緩存信息 
  12.  * @author ajun 
  13.  * @email [email protected] 
  14.  * @blog http://blog.csdn.net/ajun_studio 
  15.  * 2012-2-27 上午10:42:06 
  16.  */  
  17. @Target(ElementType.METHOD)     
  18. @Retention(RetentionPolicy.RUNTIME)      
  19. @Documented      
  20. @Inherited   
  21. public @interface Cache {  
  22.       
  23.     String prefix();//key的前綴,如諮詢:zx   
  24.   
  25.     long expiration() default 1000*60*60*2;//緩存有效期 1000*60*60*2==2小時過期   
  26.       
  27.       
  28. }  
Flush註解
  1. package com.woaika.loan.commons.annotation;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Inherited;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.RetentionPolicy;  
  8. import java.lang.annotation.Target;  
  9.   
  10. /** 
  11.  * 用於刪除緩存 
  12.  * @author ajun 
  13.  * @email [email protected] 
  14.  * @blog http://blog.csdn.net/ajun_studio 
  15.  * 2012-2-27 上午10:53:03 
  16.  */  
  17. @Target(ElementType.METHOD)     
  18. @Retention(RetentionPolicy.RUNTIME)      
  19. @Documented      
  20. @Inherited   
  21. public @interface Flush {  
  22.     String prefix();//key的前綴,如諮詢:zx   
  23. }  
臨時表用於存儲key值
  1. CREATE TABLE `cache_log` (                                     
  2.              `id` bigint(20) NOT NULL AUTO_INCREMENT,                     
  3.              `prefix` varchar(50) DEFAULT NULL COMMENT 'key的前綴',    
  4.              `cache_key` varchar(300) DEFAULT NULL COMMENT 'key值',      
  5.              `add_time` datetime DEFAULT NULL,                            
  6.              PRIMARY KEY (`id`)                                           
  7.            ) ENGINE=MyISAM DEFAULT CHARSET=utf8    
memcache客戶端代碼:需要java_memcached-release_2.6.2.jar
  1. package com.woaika.loan.commons.cache;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import com.danga.MemCached.*;   
  6. import com.woaika.loan.commons.constants.CacheConstant;  
  7. public class Memcache {  
  8.   
  9.     static MemCachedClient memCachedClient=null;  
  10.     static{  
  11.           
  12.         String[] servers = { CacheConstant.SERVIERS};    
  13.         SockIOPool pool = SockIOPool.getInstance();    
  14.           
  15.         pool.setServers(servers);    
  16.         pool.setFailover(true);    
  17.      // 設置初始連接數、最小和最大連接數以及最大處理時間    
  18.     /*    pool.setInitConn(5); 
  19.         pool.setMinConn(5); 
  20.         pool.setMaxConn(250); 
  21.         pool.setMaxIdle(1000 * 60 * 60 * 6); */  
  22.         pool.setInitConn(10);    
  23.         pool.setMinConn(5);    
  24.         pool.setMaxConn(250);    
  25.         pool.setMaintSleep(30);  // 設置主線程的睡眠時間    
  26.      // 設置TCP的參數,連接超時等    
  27.         pool.setNagle(false);    
  28.         pool.setSocketTO(3000);    
  29.         pool.setAliveCheck(true);   
  30.           
  31.         pool.initialize();    
  32.          
  33.         memCachedClient = new MemCachedClient();      
  34.         memCachedClient.setPrimitiveAsString(true);//錕斤拷錕叫夥拷   
  35.     }  
  36.     public static Object  get(String key)  
  37.     {  
  38.         return memCachedClient.get(key);  
  39.     }  
  40. //  public static Map<String,Object> gets(String[] keys)   
  41. //  {          
  42. //      return memCachedClient.getMulti(keys);   
  43. //  }   
  44.     public static boolean set(String key,Object o)  
  45.     {  
  46.         return memCachedClient.set(key, o);       
  47.     }  
  48.     public static boolean set(String key,Object o,Date ExpireTime)  
  49.     {         
  50.         return memCachedClient.set(key, o, ExpireTime);  
  51.     }  
  52.     public static boolean exists(String key)  
  53.     {  
  54.         return memCachedClient.keyExists(key);  
  55.     }  
  56.     public static boolean delete(String key)  
  57.     {  
  58.         return memCachedClient.delete(key);  
  59.     }  
  60. }  

spring AOP代碼 基於註解
  1. package com.woaika.loan.front.common.aop;  
  2.   
  3. import java.lang.reflect.Method;  
  4. import java.util.Date;  
  5. import java.util.List;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.aspectj.lang.ProceedingJoinPoint;  
  10. import org.aspectj.lang.Signature;  
  11. import org.aspectj.lang.annotation.Around;  
  12. import org.aspectj.lang.annotation.Aspect;  
  13. import org.aspectj.lang.annotation.Pointcut;  
  14. import org.aspectj.lang.reflect.MethodSignature;  
  15. import org.springframework.stereotype.Component;  
  16.   
  17. import com.woaika.loan.commons.annotation.Cache;  
  18. import com.woaika.loan.commons.annotation.Flush;  
  19. import com.woaika.loan.commons.cache.Memcache;  
  20. import com.woaika.loan.po.CacheLog;  
  21. import com.woaika.loan.service.log.ICacheLogService;  
  22.   
  23. /** 
  24.  * 攔截緩存 
  25.  * @author ajun 
  26.  * @email [email protected] 
  27.  * @blog http://blog.csdn.net/ajun_studio 
  28.  * 2012-3-12 上午10:51:58 
  29.  */  
  30. @Component  
  31. @Aspect  
  32. public class CacheAop {  
  33.   
  34.     private ICacheLogService cacheLogService;  
  35.       
  36.     @Resource(name="cacheLogService")  
  37.     public void setCacheLogService(ICacheLogService cacheLogService) {  
  38.         this.cacheLogService = cacheLogService;  
  39.     }  
  40.   
  41.       
  42.     //定義切面   
  43.     @Pointcut("execution(* com.woaika.loan.service..*.*(..))")  
  44.     public void cachedPointcut() {  
  45.   
  46.     }  
  47.   
  48.     @Around("cachedPointcut()")  
  49.     public Object doAround(ProceedingJoinPoint call){  
  50.          Object result = null;  
  51.          Method[] methods = call.getTarget().getClass().getDeclaredMethods();    
  52.          Signature signature = call.getSignature();  
  53.          MethodSignature methodSignature = (MethodSignature) signature;    
  54.          Method method = methodSignature.getMethod();  
  55.            
  56.          for(Method m:methods){//循環方法,找匹配的方法進行執行   
  57.              if(m.getName().equals(method.getName())){  
  58.                  if(m.isAnnotationPresent(Cache.class)){  
  59.                      Cache cache = m.getAnnotation(Cache.class);  
  60.                      if(cache!=null){  
  61.                             String tempKey = this.getKey(method, call.getArgs());  
  62.                             String prefix = cache.prefix();  
  63.                             String key = prefix+"_"+tempKey;  
  64.                             result =Memcache.get(key);  
  65.                             if(null == result){  
  66.                                 try {  
  67.                                     result = call.proceed();  
  68.                                     long expiration = cache.expiration();//1000*60*60*2==2小時過期   
  69.                                     Date d=new Date();  
  70.                                     d=new Date(d.getTime()+expiration);  
  71.                                     Memcache.set(key, result, d);  
  72.                                     //將key存入數據庫   
  73.                                     CacheLog log = new CacheLog();  
  74.                                     log.setPrefix(prefix);  
  75.                                     log.setCacheKey(key);  
  76.                                     this.cacheLogService.add(log);  
  77.                                 } catch (Throwable e) {  
  78.                                     e.printStackTrace();  
  79.                                 }  
  80.                             }  
  81.                               
  82.                         }  
  83.                 } else  if(method.isAnnotationPresent(Flush.class)){  
  84.                      Flush flush = method.getAnnotation(Flush.class);  
  85.                      if(flush!=null){  
  86.                             String prefix = flush.prefix();  
  87.                             List<CacheLog>  logs= cacheLogService.findListByPrefix(prefix);  
  88.                              if(logs!=null && !logs.isEmpty()){  
  89.                                  //刪除數據庫   
  90.                                 int rows =  cacheLogService.deleteByPrefix(prefix);  
  91.                                 if(rows>0){  
  92.                                     for(CacheLog log :logs){  
  93.                                         if(log!=null){  
  94.                                             String key = log.getCacheKey();  
  95.                                             Memcache.delete(key);//刪除緩存   
  96.                                         }  
  97.                                     }  
  98.                                 }  
  99.                              }  
  100.                         }  
  101.                  }else{  
  102.                      try {  
  103.                          result = call.proceed();  
  104.                         } catch (Throwable e) {  
  105.                             e.printStackTrace();  
  106.                         }  
  107.                  }  
  108.                  break;  
  109.              }  
  110.               
  111.         }  
  112.           
  113.           
  114.           
  115.         return result;  
  116.     }  
  117.       
  118.     /** 
  119.      * 組裝key值 
  120.      * @param method 
  121.      * @param args 
  122.      * @return 
  123.      */  
  124.    private String getKey(Method method, Object [] args){  
  125.         StringBuffer sb = new StringBuffer();   
  126.         String methodName = method.getName();  
  127.         sb.append(methodName);  
  128.         if(args!=null && args.length>0){  
  129.               
  130.             for(Object arg:args){  
  131.                 sb.append(arg);  
  132.             }  
  133.         }  
  134.           
  135.         return sb.toString();  
  136.          
  137.    }  
  138. }  
service層方法添加註解,但是裏面代碼沒有添加任何memcache客戶端的代碼,達到降低耦合性:
  1.  @Cache(prefix=CacheConstant.ANLI,expiration=1000*60*60*10)  
  2.  @Transactional(propagation = Propagation.NOT_SUPPORTED,readOnly=true)  
  3.     public QueryResult findAll(Integer firstIndex, Integer pageSize) {  
  4.         Map condition = new HashMap();  
  5.         return loanCaseDao.findByCondition(condition, LoanCase.class, firstIndex, pageSize);  
  6.     }  
以上是主要代碼的實現思路,希望對同志們的有所幫助,關於spring aop 自行google下就知道
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章