统一缓存处理 AOP

实现统一的缓存处理

内存的读取速度是磁盘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);
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lingchen0522

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值