前两篇文章大致实现了通用缓存,缓存加不加,哪些方法加,哪些方法不加已经实现了人为的控制,但是!!!
如果想让这个注解
@Around("execution(* com.lkl.service.*ServiceImpl.find*(..))")
生效,方法必须要以指定的方法名开头,该例子中必须要以find开头。如果方法名是QueryAll()的话,还需要另外做一个切入点,这样就没有达到通用的目的。
想要做到更加灵活,就要用到@annotation切入点表达式。代表只用该注解的方法,才会进入切面。
@Around("@annotation(com.lkl.annotations.RedisCache)")
此时,对应上面文章(redis通用缓存设计2)中就不在判断是否方法上是否存在@RedisCache这个注解了,因为@annotation这种表达式就代表有这个注解才会进入切面。
代码修改如下:
@Around("@annotation(com.lkl.annotations.RedisCache)")
public Object around(ProceedingJoinPoint pjp){
//获取key
String key = getKey(pjp);
//获取jedis对象,以默认端口号6379连接
Jedis jedis = new Jedis("192.168.1.*",6379);
Object result = null;
//判断Redis中是否存在这个key
if(jedis.exists(key)){//如果存在取出数据返回
System.out.println("the data is exist in redis,direct return ");
String json = jedis.get(key);
//把这个签名,转换为反射包中的MethodSignature
MethodSignature signature = (MethodSignature) pjp.getSignature();
System.out.println(signature.getReturnType());
result = JSONObject.parseObject(json,signature.getReturnType());
}else{ //如果不存在,放行Dao方法执行存入Redis中
System.out.println("the data is not exist in redis,query the DB");
try {
result = pjp.proceed();//放行
//放入redis中,以json形式存入
jedis.set(key,JSONObject.toJSONString(result));
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
return result;
}