添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
其余在spring环境。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface YdCache {
//缓存时长
long time() default -1L;
}
@Aspect
@Component
public class SysCacheAspect {
@Resource
StringRedisTemplate stringRedisTemplate;
@Around("@annotation(com.example.mybatisplus.aspect.YdCache)")
public Object around(ProceedingJoinPoint point) throws Throwable {
//取得方法签名
MethodSignature signature = (MethodSignature) point.getSignature();
//取得方法对象
Method method = signature.getMethod();
//取得缓存注解对象
YdCache ydCache = method.getAnnotation(YdCache.class);
//取得注解上的缓存时长
long cacheTime = ydCache.time();
//redis的key为类名:方法名:参数
String className = point.getTarget().getClass().getName();
String methodName = signature.getName();
String argsJson = JSON.toJSONString(point.getArgs());
String key = className + ":" + methodName + ":" + argsJson;
//取得返回值类类型
Class<?> returnType = method.getReturnType();
//从缓存取得数据
String cacheData = stringRedisTemplate.opsForValue().get(key);
//命中缓存
if (cacheData != null) {
//返回缓存数据
return JSON.parseObject(cacheData, returnType);
}
//没命中缓存 执行方法
Object result = point.proceed();
//设置缓存,缓存时长为负数则永久缓存
if (cacheTime < 0) {
stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(result));
} else {
//缓存指定时长
stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(result), cacheTime, TimeUnit.SECONDS);
}
return result;
}
}
在方法上添加注解即可,time为缓存时间