您的位置:首页 > 数据库 > Memcache

利用Spring AOP 更新Memcached 缓存策略的实现

2015-04-26 05:11 806 查看
对于网上关于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注解

package com.woaika.loan.commons.annotation;  
  
import java.lang.annotation.Documented;  
import java.lang.annotation.ElementType;  
import java.lang.annotation.Inherited;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
  
/** 
 * 用于在查询的时候 ,放置缓存信息 
 * @author ajun 
 * @email zhaojun2066@gmail.com 
 * @blog http://blog.csdn.net/ajun_studio 
 * 2012-2-27 上午10:42:06 
 */  
@Target(ElementType.METHOD)     
@Retention(RetentionPolicy.RUNTIME)      
@Documented      
@Inherited   
public @interface Cache {  
      
    String prefix();//key的前缀,如咨询:zx   
  
    long expiration() default 1000*60*60*2;//缓存有效期 1000*60*60*2==2小时过期   
      
      
}  

Flush注解

package com.woaika.loan.commons.annotation;  
  
import java.lang.annotation.Documented;  
import java.lang.annotation.ElementType;  
import java.lang.annotation.Inherited;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
  
/** 
 * 用于删除缓存 
 * @author ajun 
 * @email zhaojun2066@gmail.com 
 * @blog http://blog.csdn.net/ajun_studio 
 * 2012-2-27 上午10:53:03 
 */  
@Target(ElementType.METHOD)     
@Retention(RetentionPolicy.RUNTIME)      
@Documented      
@Inherited   
public @interface Flush {  
    String prefix();//key的前缀,如咨询:zx   
}  

临时表用于存储key值

CREATE TABLE `cache_log` (                                     
             `id` bigint(20) NOT NULL AUTO_INCREMENT,                     
             `prefix` varchar(50) DEFAULT NULL COMMENT 'key的前缀',    
             `cache_key` varchar(300) DEFAULT NULL COMMENT 'key值',      
             `add_time` datetime DEFAULT NULL,                            
             PRIMARY KEY (`id`)                                           
           ) ENGINE=MyISAM DEFAULT CHARSET=utf8    

memcache客户端代码:需要java_memcached-release_2.6.2.jar

package com.woaika.loan.commons.cache;  
  
import java.util.Date;  
  
import com.danga.MemCached.*;   
import com.woaika.loan.commons.constants.CacheConstant;  
public class Memcache {  
  
    static MemCachedClient memCachedClient=null;  
    static{  
          
        String[] servers = { CacheConstant.SERVIERS};    
        SockIOPool pool = SockIOPool.getInstance();    
          
        pool.setServers(servers);    
        pool.setFailover(true);    
     // 设置初始连接数、最小和最大连接数以及最大处理时间    
    /*    pool.setInitConn(5); 
        pool.setMinConn(5); 
        pool.setMaxConn(250); 
        pool.setMaxIdle(1000 * 60 * 60 * 6); */  
        pool.setInitConn(10);    
        pool.setMinConn(5);    
        pool.setMaxConn(250);    
        pool.setMaintSleep(30);  // 设置主线程的睡眠时间    
     // 设置TCP的参数,连接超时等    
        pool.setNagle(false);    
        pool.setSocketTO(3000);    
        pool.setAliveCheck(true);   
          
        pool.initialize();    
         
        memCachedClient = new MemCachedClient();      
        memCachedClient.setPrimitiveAsString(true);//锟斤拷锟叫伙拷   
    }  
    public static Object  get(String key)  
    {  
        return memCachedClient.get(key);  
    }  
//  public static Map<String,Object> gets(String[] keys)   
//  {          
//      return memCachedClient.getMulti(keys);   
//  }   
    public static boolean set(String key,Object o)  
    {  
        return memCachedClient.set(key, o);       
    }  
    public static boolean set(String key,Object o,Date ExpireTime)  
    {         
        return memCachedClient.set(key, o, ExpireTime);  
    }  
    public static boolean exists(String key)  
    {  
        return memCachedClient.keyExists(key);  
    }  
    public static boolean delete(String key)  
    {  
        return memCachedClient.delete(key);  
    }  
}  

spring AOP代码 基于注解

package com.woaika.loan.front.common.aop;  
  
import java.lang.reflect.Method;  
import java.util.Date;  
import java.util.List;  
  
import javax.annotation.Resource;  
  
import org.aspectj.lang.ProceedingJoinPoint;  
import org.aspectj.lang.Signature;  
import org.aspectj.lang.annotation.Around;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Pointcut;  
import org.aspectj.lang.reflect.MethodSignature;  
import org.springframework.stereotype.Component;  
  
import com.woaika.loan.commons.annotation.Cache;  
import com.woaika.loan.commons.annotation.Flush;  
import com.woaika.loan.commons.cache.Memcache;  
import com.woaika.loan.po.CacheLog;  
import com.woaika.loan.service.log.ICacheLogService;  
  
/** 
 * 拦截缓存 
 * @author ajun 
 * @email zhaojun2066@gmail.com 
 * @blog http://blog.csdn.net/ajun_studio 
 * 2012-3-12 上午10:51:58 
 */  
@Component  
@Aspect  
public class CacheAop {  
  
    private ICacheLogService cacheLogService;  
      
    @Resource(name="cacheLogService")  
    public void setCacheLogService(ICacheLogService cacheLogService) {  
        this.cacheLogService = cacheLogService;  
    }  
  
      
    //定义切面   
    @Pointcut("execution(* com.woaika.loan.service..*.*(..))")  
    public void cachedPointcut() {  
  
    }  
  
    @Around("cachedPointcut()")  
    public Object doAround(ProceedingJoinPoint call){  
         Object result = null;  
         Method[] methods = call.getTarget().getClass().getDeclaredMethods();    
         Signature signature = call.getSignature();  
         MethodSignature methodSignature = (MethodSignature) signature;    
         Method method = methodSignature.getMethod();  
           
         for(Method m:methods){//循环方法,找匹配的方法进行执行   
             if(m.getName().equals(method.getName())){  
                 if(m.isAnnotationPresent(Cache.class)){  
                     Cache cache = m.getAnnotation(Cache.class);  
                     if(cache!=null){  
                            String tempKey = this.getKey(method, call.getArgs());  
                            String prefix = cache.prefix();  
                            String key = prefix+"_"+tempKey;  
                            result =Memcache.get(key);  
                            if(null == result){  
                                try {  
                                    result = call.proceed();  
                                    long expiration = cache.expiration();//1000*60*60*2==2小时过期   
                                    Date d=new Date();  
                                    d=new Date(d.getTime()+expiration);  
                                    Memcache.set(key, result, d);  
                                    //将key存入数据库   
                                    CacheLog log = new CacheLog();  
                                    log.setPrefix(prefix);  
                                    log.setCacheKey(key);  
                                    this.cacheLogService.add(log);  
                                } catch (Throwable e) {  
                                    e.printStackTrace();  
                                }  
                            }  
                              
                        }  
                } else  if(method.isAnnotationPresent(Flush.class)){  
                     Flush flush = method.getAnnotation(Flush.class);  
                     if(flush!=null){  
                            String prefix = flush.prefix();  
                            List<CacheLog>  logs= cacheLogService.findListByPrefix(prefix);  
                             if(logs!=null && !logs.isEmpty()){  
                                 //删除数据库   
                                int rows =  cacheLogService.deleteByPrefix(prefix);  
                                if(rows>0){  
                                    for(CacheLog log :logs){  
                                        if(log!=null){  
                                            String key = log.getCacheKey();  
                                            Memcache.delete(key);//删除缓存   
                                        }  
                                    }  
                                }  
                             }  
                        }  
                 }else{  
                     try {  
                         result = call.proceed();  
                        } catch (Throwable e) {  
                            e.printStackTrace();  
                        }  
                 }  
                 break;  
             }  
              
        }  
          
          
          
        return result;  
    }  
      
    /** 
     * 组装key值 
     * @param method 
     * @param args 
     * @return 
     */  
   private String getKey(Method method, Object [] args){  
        StringBuffer sb = new StringBuffer();   
        String methodName = method.getName();  
        sb.append(methodName);  
        if(args!=null && args.length>0){  
              
            for(Object arg:args){  
                sb.append(arg);  
            }  
        }  
          
        return sb.toString();  
         
   }  
}  

service层方法添加注解,但是里面代码没有添加任何memcache客户端的代码,达到降低耦合性:

 @Cache(prefix=CacheConstant.ANLI,expiration=1000*60*60*10)  
 @Transactional(propagation = Propagation.NOT_SUPPORTED,readOnly=true)  
    public QueryResult findAll(Integer firstIndex, Integer pageSize) {  
        Map condition = new HashMap();  
        return loanCaseDao.findByCondition(condition, LoanCase.class, firstIndex, pageSize);  
    }  

以上是主要代码的实现思路,希望对同志们的有所帮助,关于spring aop 自行google下就知道
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  aop spring