自定义Redis注解及切面导入

1.切面类
@Aspect
@Component
public class DelRedisAspect {

    public static final Logger logger = LoggerFactory.getLogger(DelRedisAspect.class);

    @Autowired
    RedisClient redisClient;
    /**
     * 切换到product主库
     *
     * @param joinPoint
     * @param delRedis
     * @return
     * @throws Throwable
     */
    @Around("@annotation(delRedis)")
    private Object proceed(ProceedingJoinPoint joinPoint, DelRedis delRedis) throws Throwable {

        Method method=getMethod(joinPoint);
        StringBuilder key = new StringBuilder(delRedis.key());
        String fieldKey =parseKey(delRedis.fieldKey(),method,joinPoint.getArgs());
        key.append(fieldKey);
        redisClient.del(key.toString());
        // result的值就是被拦截方法的返回值
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long timeConsuming = System.currentTimeMillis() - start;

        logger.info("请求结束, 耗时 :{} s, controller的返回值是 :{}" ,timeConsuming/1000.0, result.toString());
        return result;

    }

    // 在使用Cache注解的地方切入此切点
    @Around("@annotation(putRedis)")
    private Object proceed(ProceedingJoinPoint pjp,PutRedis putRedis) throws Throwable {
        System.out.println("以下是缓存逻辑");
        // 获取切入的方法对象
        // 这个m是代理对象的,没有包含注解
        Method m = ((MethodSignature) pjp.getSignature()).getMethod();
        // this()返回代理对象,target()返回目标对象,目标对象反射获取的method对象才包含注解
        Method methodWithAnnotations = pjp.getTarget().getClass().getDeclaredMethod(pjp.getSignature().getName(), m.getParameterTypes());
        // 根据目标方法对象获取注解对象
        // 解析key
        StringBuilder key = new StringBuilder(putRedis.key());
        String keyExpr = putRedis.fieldKey();
        Object[] as = pjp.getArgs();
        String fieldKey = parseKey(keyExpr, methodWithAnnotations, as);
        key.append(fieldKey);
        // 注解的属性本质是注解里的定义的方法
//        Method methodOfAnnotation = a.getClass().getMethod("key");
        // 注解的值本质是注解里的定义的方法返回值
//        String key = (String) methodOfAnnotation.invoke(a);
        // 到redis中获取缓存
        String stringKey = key.toString();
        Class returnType=((MethodSignature)pjp.getSignature()).getReturnType();
        Object cache = redisClient.get(stringKey, returnType);
        if (cache == null) {
            // 若不存在,则到数据库中去获取
            Object result = pjp.proceed();

            if (!isNull(result)){

                // 从数据库获取后存入redis
                System.out.println("从数据库获取的结果以JsonString形式存入redis中[{"+JSON.toJSONString(result)+"}]");
                redisClient.set(stringKey, JSON.toJSONString(result));
                // 若有指定过期时间,则设置
                int expireTime = putRedis.expire();
                if (expireTime != -1) {
                    redisClient.expire(stringKey,expireTime);
                }

            }

            return result;
        } else {
            return cache;
        }
    }

    /**
     *  获取被拦截方法对象
     *
     *  MethodSignature.getMethod() 获取的是顶层接口或者父类的方法对象
     *    而缓存的注解在实现类的方法上
     *  所以应该使用反射获取当前对象的方法对象
     */
    public Method getMethod(ProceedingJoinPoint pjp){
        //获取参数的类型
        Object [] args=pjp.getArgs();
        Class [] argTypes=new Class[pjp.getArgs().length];
        for(int i=0;i<args.length;i++){
            argTypes[i]=args[i].getClass();
        }
        Method method=null;
        try {
            method=pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(),argTypes);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return method;

    }

    /**
     *    获取缓存的key
     *    key 定义在注解上,支持SPEL表达式
     * @param key
     * @return
     */
    private String parseKey(String key,Method method,Object [] args){


        //获取被拦截方法参数名列表(使用Spring支持类库)
        LocalVariableTableParameterNameDiscoverer u =
                new LocalVariableTableParameterNameDiscoverer();
        String [] paraNameArr=u.getParameterNames(method);

        //使用SPEL进行key的解析
        ExpressionParser parser = new SpelExpressionParser();
        //SPEL上下文
        StandardEvaluationContext context = new StandardEvaluationContext();
        //把方法参数放入SPEL上下文中
        for(int i=0;i<paraNameArr.length;i++){
            context.setVariable(paraNameArr[i], args[i]);
        }
        return parser.parseExpression(key).getValue(context,String.class);
    }

    private boolean isNull(Object object){
        Collection collection = null;
        if(object instanceof Collection) {
            collection =  (Collection) object;
            return collection.isEmpty();
        } else if(object instanceof Map) {
            Map map = (Map) object;
            collection =  map.entrySet();
            return collection.isEmpty();//Set
        } else {
            if (object==null){
                return true;
            }
        }
        return false;
    }

}


2.注解类
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PutRedis {
    String key();
    String fieldKey();
    int expire() default 3600;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于SpringBoot自定义Redis注解AOP的问题,我可以为您提供一些基本的介绍和示例代码。 Redis作为一种高性能的缓存和数据存储解决方案,被广泛应用于各种应用程序中。在SpringBoot应用程序中,使用Redis通常需要编写大量的重复代码,比如获取Redis连接、执行Redis命令、释放Redis连接等。这些重复代码不仅增加了开发和维护的难度,还影响了应用程序的性能。而AOP作为一种切面编程的技术,可以很好地解决这些问题。 下面是一个简单的示例代码,演示如何通过自定义注解实现对Redis操作的AOP处理: 首先,定义一个自定义注解: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RedisCacheable { String key() default ""; long expire() default 0; } ``` 然后,在需要被拦截的方法上添加该注解: ```java @Component public class RedisService { @Autowired private RedisTemplate<String, String> redisTemplate; @RedisCacheable(key = "myKey", expire = 60) public String getValue() { return redisTemplate.opsForValue().get("myKey"); } } ``` 接下来,使用AspectJ的@Aspect注解定义一个切面类,并在该类中定义一个切点,用于匹配被@RedisCacheable注解的方法: ```java @Aspect @Component public class RedisAspect { @Autowired private RedisTemplate<String, String> redisTemplate; @Pointcut("@annotation(com.example.demo.annotation.RedisCacheable)") public void redisCacheablePointcut() {} @Around("redisCacheablePointcut()") public Object aroundRedisCacheable(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); RedisCacheable redisCacheable = method.getAnnotation(RedisCacheable.class); String key = redisCacheable.key(); long expire = redisCacheable.expire(); String value = redisTemplate.opsForValue().get(key); if (value != null) { return value; } Object result = joinPoint.proceed(); if (result != null) { redisTemplate.opsForValue().set(key, result.toString()); if (expire > 0) { redisTemplate.expire(key, expire, TimeUnit.SECONDS); } } return result; } } ``` 在该切面类中,使用@Around注解定义一个环绕通知,在该通知中,首先获取被拦截方法上的@RedisCacheable注解,然后根据注解中的key值从Redis中获取数据。如果Redis中已经存在该数据,则直接返回;否则,执行被拦截方法,并将结果存储到Redis缓存中。 最后,启动SpringBoot应用程序,调用RedisService的getValue方法,就可以看到输出结果: ```java // 第一次调用,从数据库中获取数据,并将数据存入Redis缓存中 getValue... // 第二次调用,直接从Redis中获取数据 getValue... ``` 以上就是一个简单的SpringBoot自定义Redis注解AOP的示例。通过使用自定义注解和AOP技术,可以更加方便地实现对Redis缓存的操作,并提高应用程序的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值