AOP+自定义注解,实现redis缓存

添加如下依赖

    <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为缓存时间
在方法上添加注解即可,time为缓存时间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值