自定义aop缓存注解

package com.xs.common.redis.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XsCache {
    //缓存时长 单位秒 固定时长请输入合法数字,小于等于0的字符串都是永不失效。默认-1永不失效。
    // 区间时长输入如0#60,缓存0至60秒随机。 参数不合法则不缓存,起始时间不能小于等于0,不能大于结束时间
    String time() default "-1";
    // 若返回类型是集合类型,则指定 集合元素的类型
    Class arrayClassType() default Object.class;
}

package com.xs.common.redis.aspect;

import com.alibaba.fastjson.JSON;
import com.xs.common.redis.annotation.XsCache;
import com.xs.common.redis.annotation.XsCacheDelete;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Aspect
@Component
@Order(Integer.MIN_VALUE)
public class BusCacheAspect {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Around("@annotation(com.xs.common.redis.annotation.XsCache)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //取得方法签名
        MethodSignature signature = (MethodSignature) point.getSignature();
        //取得方法对象
        Method method = signature.getMethod();
        //取得缓存注解对象
        XsCache xsCache = method.getAnnotation(XsCache.class);
        //取得注解上的缓存时长
        String time = xsCache.time();
        // 获取 缓存时间
        Long cacheTime = getCacheTime(time);
        //redis的key为类名:方法名:参数
        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        Object[] args = point.getArgs();
        String hashKey = DigestUtils.md5DigestAsHex(JSON.toJSONString(args).getBytes(StandardCharsets.UTF_8));
        String key = "buscache" + ":" + className + ":" + methodName;
        //取得返回值类类型
        Class<?> returnType = method.getReturnType();
        //从缓存取得数据
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(key);
        String cacheData = ops.get(hashKey);
        //命中缓存
        if (cacheData != null) {
            //返回缓存数据
            // 若是数组
            if (Collection.class.isAssignableFrom(returnType)){
                //取得注解上的集合的元素类类型
                Class arrayClassType = xsCache.arrayClassType();
                return JSON.parseArray(cacheData,arrayClassType);
            }else {
                return JSON.parseObject(cacheData, returnType);
            }
        }
        //没命中缓存 执行方法
        Object result = point.proceed();
        //设置缓存,缓存时长为负数则永久缓存
        if (!cacheTime.equals(0L)) {
            if (cacheTime.equals(-1L)) {
                // 缓存永久
                ops.put(hashKey, JSON.toJSONString(result));
            } else {
                //缓存指定时长
                ops.put(hashKey, JSON.toJSONString(result));
                ops.expire(cacheTime, TimeUnit.SECONDS);
            }
        }
        return result;
    }

    private Long getCacheTime(String time) {
        Long cacheTime;
        try {
            if (time.contains("#")) {
                // 随机时长类型
                String[] timeInterval = time.split("#");
                Long start = Long.valueOf(timeInterval[0]);
                if (start.compareTo(0L) <= 0) {
                    throw new RuntimeException("随机起始时间不能等于小于0");
                }
                Long end = Long.valueOf(timeInterval[1]);
                if (start.compareTo(end) > 0) {
                    throw new RuntimeException("随机起始时间不能大于结束时间");
                }
                Random r = new Random();
                cacheTime = start + ((long) (r.nextDouble() * (end - start)));
            } else {
                // 固定时长类型
                Long temp = Long.valueOf(time);
                if (temp.compareTo(0L) <= 0) {
                    cacheTime = -1L;
                } else {
                    cacheTime = temp;
                }
            }
        } catch (Exception e) {
            // 参数不合法 默认0
            cacheTime = 0L;
        }
        return cacheTime;
    }

    @Before("@annotation(com.xs.common.redis.annotation.XsCacheDelete)")
    public void beforeAdvice(JoinPoint point) {
        //取得方法签名
        MethodSignature signature = (MethodSignature) point.getSignature();
        //取得方法对象
        Method method = signature.getMethod();
        //取得缓存注解对象
        XsCacheDelete xsCacheDelete = method.getAnnotation(XsCacheDelete.class);
        //取得注解上待删除的key
        String k = xsCacheDelete.key();
        stringRedisTemplate.delete(k);
    }

}

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
@XsCache(time = "720#1080")
package com.xs.common.redis.annotation;


import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XsCacheDelete {
    // 需要删除的缓存key
    String key();
}

@XsCacheDelete(key = "buscache:com.xs.thirdparty.service.impl.TaskAccessRecordServiceImpl:queryCareRule")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值