SpringBoot Redis 缓存失效设置(手写)

第一步 

//创建一个注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisCache {
     String Value() default "";
     long time() default 0L;
}

第二步写一个拦截器

@Aspect
@Order(1) //拦截器执行顺序
@Component
public class Interceptor {

    /**
     * redis 模板注入
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Pointcut("@annotation(redisCache)")
    public void pointCut(RedisCache redisCache) {}

    /**
     * 环绕通知
     * @param proceedingJoinPoint
     * @param redisCache
     * @return
     * @throws Throwable
     */
    @Around("pointCut(redisCache)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint,RedisCache redisCache) throws Throwable {
        //目标方法执行前
        String value = redisCache.Value();
        // 查询redis数据 
        // ResponseData 封装一个类用来接收返回数据
        ResponseData result = (ResponseData) redisTemplate.opsForValue().get(value);
        if(null == result || result.getCode() != 200){
            //执行目标方法
            result = (ResponseData) proceedingJoinPoint.proceed();
            //目标方法执行后
            long time = redisCache.time();
            if (time > 0L)
                redisTemplate.opsForValue().set(value,result, time, TimeUnit.MILLISECONDS);
            else if(time <= 0L)
                redisTemplate.opsForValue().set(value,result);
        }
        return result;
    }

}

测试

 //value 缓存 key值 time 时间毫秒
 @RedisCache(Value = "value",time = 15000)
 @GetMapping("/index")
 public ResponseData getIndex() {
    System.out.println("执行方法了");
    return ResponseData.success("123213");
 }

封装

public class ResponseData {

    private boolean isSuccess;

    private int code;

    private Object body;

    public ResponseData() {}

    private ResponseData(boolean isSuccess, Object body) {
        this.isSuccess = isSuccess;
        this.body = body;
    }

    public static ResponseData success(Object body) {
        return new ResponseData(200,body);
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章