redis通用缓存设计(3)

前两篇文章大致实现了通用缓存,缓存加不加,哪些方法加,哪些方法不加已经实现了人为的控制,但是!!!

如果想让这个注解

@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;

    }

 

转载于:https://www.cnblogs.com/lkldeblog/p/11276867.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值