实现统一的缓存处理
内存的读取速度是磁盘IO 的 103 ~ 10 6 倍,实现缓存,可以有效地提供读取速度,加速页面的响应。
自定义 Cache 注解
import java.lang.annotation.*;
/**
* @Author 凌宸
* @create 2021-12-18 下午 10:09
* @Description
* @Version 1.0
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Cache {
// 设置过期时间,默认值是 1 分钟
long expire() default 1 * 60 * 1000;
// 缓存标识 key
String name() default "";
}
创建 CacheAspect 类,定义切面和通知的关系
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import top.lingchen.blogapi.vo.Result;
import java.lang.reflect.Method;
import java.time.Duration;
/**
* @Author 凌宸
* @create 2021-12-18 下午 10:12
* @Description
* @Version 1.0
*/
// aop 定义一个切面,切面定义了切点和通知的关系
@Aspect
@Component
@Slf4j
public class CacheAspect {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Pointcut("@annotation(top.lingchen.blogapi.cache.Cache)")
public void pt(){
}
@Around("pt()")
public Object around(ProceedingJoinPoint point){
try{
Signature signature = point.getSignature();
// 类名
String className = point.getTarget().getClass().getSimpleName();
// 调用的方法名
String methodName = signature.getName();
// 获取参数类型和参数值
Class[] parameterTypes = new Class[point.getArgs().length];
Object[] args = point.getArgs();
//参数
String params = "";
for(int i = 0; i < args.length; i++) {
if(args[i] != null) {
params += JSON.toJSONString(args[i]);
parameterTypes[i] = args[i].getClass();
}else {
parameterTypes[i] = null;
}
}
if (StringUtils.isNotEmpty(params)) {
//加密 以防出现key过长以及字符转义获取不到的情况
params = DigestUtils.md5Hex(params);
}
Method method = point.getSignature().getDeclaringType()
.getMethod(methodName, parameterTypes);
//获取Cache注解
Cache annotation = method.getAnnotation(Cache.class);
//缓存过期时间
long expire = annotation.expire();
//缓存名称
String name = annotation.name();
//先从redis获取
String redisKey = name + "::" + className+"::"+methodName+"::"+params;
String redisValue = stringRedisTemplate.opsForValue().get(redisKey);
if (StringUtils.isNotEmpty(redisValue)){
log.info("走了缓存~~~,{},{}",className,methodName);
return JSON.parseObject(redisValue, Result.class);
}
Object proceed = point.proceed();
stringRedisTemplate.opsForValue()
.set(redisKey,JSON.toJSONString(proceed), Duration.ofMillis(expire));
log.info("存入缓存~~~ {},{}",className,methodName);
return proceed;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return Result.fail(-999,"系统错误");
}
}
Result 类是后端提供给前端的数据的封装
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @Author 凌宸
* @create 2021-12-15 下午 9:01
* @Description
* @Version 1.0
*/
@Data
@AllArgsConstructor
public class Result {
// 方法返回是否是成功
private boolean success;
// 返回代码
private int code;
// 返回信息
private String msg;
// 返回数据
private Object data;
public static Result success(Object data){
return new Result(true, 200, "success", data);
}
public static Result fail(int code, String msg){
return new Result(false, code, msg, null);
}
}
使用,在需要进行缓存处理的方法上添加 @Cache 注解
@Autowired
ArticleService articleService;
/**
* 首页 分页查询文章列表 /articles
* @param params 包含 页码和每页显示输了
* @return
*/
@PostMapping
@LogAnnotation(module = "文章", operator = "获取文章列表")
@Cache(expire = 5 * 60 * 1000, name = "listArticle")
public Result listArticle(@RequestBody PageParams params){
return articleService.listArticle(params);
}