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);
    }

}

 

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