自定义注解+aop实现jetcache功能扩展

        <!--引入AOP依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

创建注解类

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RemoveCache {
    String key() default "";
    String value() default "[null,null]";
}

引用注解

 @RemoveCache(key = "TestController.getTest:")
    @RequestMapping("/update")
    public Object update(){
        //return testService.update(new UpdateWrapper<Test>().eq("id",test.getId()).set("name",test.getName()).set("age",test.getAge()));
        return 0;
    }

aop的创建

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.test.Controller.RemoveCache;

import java.lang.reflect.Method;

/**
 * @author huQi
 * @email
 * @data 2021/2/3 10:08
 */
@Aspect
@Component
public class MyCache {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Around("@annotation(org.test.Controller.RemoveCache)")
    public Object target(ProceedingJoinPoint pjp) {
        Object ob = null;
        try{
            Method[] methods = pjp.getTarget().getClass().getDeclaredMethods();
            for(Method method:methods){
                if(method.isAnnotationPresent(RemoveCache.class)){
                    String key = method.getAnnotation(RemoveCache.class).key();
                    String value = method.getAnnotation(RemoveCache.class).value();
                    boolean b = redisTemplate.opsForValue().getOperations().delete(key+value);

                }
            }
            ob = pjp.proceed();
        } catch (Throwable e) {

        } finally {

        }
        return ob;
    }
}
原文地址:https://www.cnblogs.com/huqi96/p/14365881.html