设为首页 收藏本站
查看: 920|回复: 0

[经验分享] 利用Spring AOP 更新memcached 缓存策略的实现

[复制链接]
发表于 2015-11-18 13:34:53 | 显示全部楼层 |阅读模式
  对于网上关于memcached缓存更新策略 数不胜数,但是没有一遍完整的,看起来都很费劲,由于项目中用到的memcache,自然就想到了memcache缓存更新策略的实现。
  你可以把你更新缓存的代码嵌套你的代码中,但是这样很不好,混换了你service的代码,要是以后再换别的缓存产品,那么你还要每个类去找,去修改很是麻烦。由于之前是这样写的,很是痛苦,所以这次要用spring aop来实现。
  在做本次试验之前 ,首先要准备好memcache,具体安装步骤请参考:http://blog.iyunv.com/ajun_studio/article/details/6745341     



  了解memcache,请参考:对memcached使用的总结和使用场景
  


  下面说以下具体更新策略的实现思路:
  首先我们会定义两个注解类,来说明是插入(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.iyunv.com/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.iyunv.com/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.iyunv.com/ajun_studio
* 2012-3-12 上午10:51:58
*/
@Component
@Aspect
public class CacheAop {
private ICacheLogService cacheLogService;
@Resource(name=&quot;cacheLogService&quot;)
public void setCacheLogService(ICacheLogService cacheLogService) {
this.cacheLogService = cacheLogService;
}
//定义切面
@Pointcut(&quot;execution(* com.woaika.loan.service..*.*(..))&quot;)
public void cachedPointcut() {
}
@Around(&quot;cachedPointcut()&quot;)
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+&quot;_&quot;+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下就知道了


  


  





版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-140746-1-1.html 上篇帖子: memcached源码学习-内存管理机制slab allocator 下篇帖子: kestrel利用dubbo和memcached协议实现 队列服务
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表