第一步 
//创建一个注解 @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); } }
 

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信