基于AOP注解的方式实现查询和设置redis缓存

一、自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface RedisCache {

    String key() default "";

    long expire() default 1;

    TimeUnit TIME_UNIT() default TimeUnit.HOURS;

    Class clazz() default Object.class;

    boolean isArray() default false;

}

二、AOP切面环绕通知

@Component
@Aspect
public class RedisCacheAspect {
    private static final Logger log = LoggerFactory.getLogger(RedisCacheAspect.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Around("@annotation(com.xxx.xxx.web.aspect.RedisCache)")
    public Object cacheInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取到目标方法
        Method method = joinPoint.getTarget().getClass().getMethod(signature.getName(), signature.getParameterTypes());
        // 获取方法注解
        RedisCache redisCache = method.getAnnotation(RedisCache.class);
        String redisKey = redisCache.key();
        if ( redisKey.indexOf("#") > -1 ) {
            // 创建解析器,解析EL表达式
            Expression expression = new SpelExpressionParser().parseExpression(redisKey);
            // 设置解析上下文
            EvaluationContext context = new StandardEvaluationContext();
            // 参数值 获取到参数实际的值
            Object[] args = joinPoint.getArgs();
            // 调用LocalVariableTableParameterNameDiscoverer去实现
            DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
            String[] parameterNames = discoverer.getParameterNames(method);
            for (int i = 0; i < parameterNames.length; i++) {
                context.setVariable(parameterNames[i], args[i]);
            }
            // 解析出key的真实值
            redisKey = expression.getValue(context).toString();
        }
        log.info("redisKey: {}", redisKey);
        String value = stringRedisTemplate.opsForValue().get(redisKey);
        if ( value == null ) {
            // 获取方法执行结果
            Object data = joinPoint.proceed();
            stringRedisTemplate.opsForValue().set(redisKey, JSON.toJSONString(data), redisCache.expire(), redisCache.TIME_UNIT());
            return data;
        }
        log.info("从redis获取...");
        return redisCache.isArray() ? JSON.parseArray(value, redisCache.clazz()) : JSON.parseObject(value, redisCache.clazz());
    }
}

三、使用场景

@Service
public class PropConfigServiceImpl extends ServiceImpl<PropConfigDao, PropConfig> implements PropConfigService {

    @Override
    public String getValueByKey(String key) {
        Wrapper<PropConfig> wrapper = new EntityWrapper<>();
        wrapper.eq("prop_key", key);
        PropConfig propConfig = this.selectOne(wrapper);
        if ( propConfig != null ) {
            return propConfig.getPropValue();
        }
        return null;
    }

    @RedisCache(key = "aaaList", expire = 7, TIME_UNIT = TimeUnit.DAYS, clazz = String.class, isArray = true)
    @Override
    public List<String> getCacheValue(String key) {
        return JSON.parseArray(getValueByKey(key), String.class);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

嘿丶小伙计

请赏我点铜板买喵粮自己吃,谢谢

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

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

打赏作者

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

抵扣说明:

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

余额充值