• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Redis+自定义注解+AOP实现声明式注解缓存查询的示例

    发布者: Error | 发布时间: 2025-6-19 12:36| 查看数: 78| 评论数: 0|帖子模式

    引言:为什么需要声明式缓存?


    • 背景痛点:传统代码中缓存逻辑与业务逻辑高度耦合,存在重复代码、维护困难等问题(如手动判断缓存存在性、序列化/反序列化操作)
    • 解决方案:通过注解+AOP实现缓存逻辑与业务解耦,开发者只需关注业务,通过注解配置缓存策略(如过期时间、防击穿机制等)
    • 技术价值:提升代码可读性、降低维护成本、支持动态缓存策略扩展。
    核心流程设计
    1. 方法调用 → 切面拦截 → 生成缓存Key → 查询Redis →
    2. └ 命中 → 直接返回缓存数据
    3. └ 未命中 → 加锁查DB → 结果写入Redis → 返回数据
    复制代码
    二、核心实现步骤


    1. 定义自定义缓存注解(如@RedisCache)
    1. package com.mixchains.ytboot.common.annotation;

    2. import java.lang.annotation.ElementType;
    3. import java.lang.annotation.Retention;
    4. import java.lang.annotation.RetentionPolicy;
    5. import java.lang.annotation.Target;
    6. import java.util.concurrent.TimeUnit;

    7. /**
    8. * @author 卫相yang
    9. * OverSion03
    10. */
    11. @Target(ElementType.METHOD)
    12. @Retention(RetentionPolicy.RUNTIME)
    13. public @interface RedisCache {
    14.     /**
    15.      * Redis键前缀(支持SpEL表达式)
    16.      */
    17.     String key();

    18.     /**
    19.      * 过期时间(默认1天)
    20.      */
    21.     long expire() default 1;

    22.     /**
    23.      * 时间单位(默认天)
    24.      */
    25.     TimeUnit timeUnit() default TimeUnit.DAYS;

    26.     /**
    27.      * 是否缓存空值(防穿透)
    28.      */
    29.     boolean cacheNull() default true;
    30. }
    复制代码
    2. 编写AOP切面(核心逻辑)

    切面职责

    • 缓存Key生成:拼接类名、方法名、参数哈希(MD5或SpEL动态参数)本次使用的是SpEL
    • 缓存查询:优先从Redis读取,使用FastJson等工具反序列化  
    空值缓存:缓存
    1. NULL
    复制代码
    值并设置短过期时间,防止恶意攻击
    1. package com.mixchains.ytboot.common.aspect;

    2. import com.alibaba.fastjson.JSON;
    3. import com.mixchains.ytboot.common.annotation.RedisCache;
    4. import io.micrometer.core.instrument.util.StringUtils;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.aspectj.lang.ProceedingJoinPoint;
    7. import org.aspectj.lang.annotation.Around;
    8. import org.aspectj.lang.annotation.Aspect;
    9. import org.aspectj.lang.reflect.MethodSignature;
    10. import org.springframework.beans.factory.annotation.Autowired;
    11. import org.springframework.core.DefaultParameterNameDiscoverer;
    12. import org.springframework.core.ParameterNameDiscoverer;
    13. import org.springframework.data.redis.core.RedisTemplate;
    14. import org.springframework.expression.EvaluationContext;
    15. import org.springframework.expression.ExpressionParser;
    16. import org.springframework.expression.spel.standard.SpelExpressionParser;
    17. import org.springframework.expression.spel.support.StandardEvaluationContext;
    18. import org.springframework.stereotype.Component;

    19. import java.lang.reflect.Method;
    20. import java.lang.reflect.Type;

    21. /**
    22. * @author 卫相yang
    23. * OverSion03
    24. */
    25. @Aspect
    26. @Component
    27. @Slf4j
    28. public class RedisCacheAspect {
    29.     @Autowired
    30.     private RedisTemplate<String, String> redisTemplate;

    31.     private final ExpressionParser parser = new SpelExpressionParser();
    32.     private final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    33.     @Around("@annotation(redisCache)")
    34.     public Object around(ProceedingJoinPoint joinPoint, RedisCache redisCache) throws Throwable {
    35.         Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    36.         // 解析SpEL表达式生成完整key
    37.         String key = parseKey(redisCache.key(), method, joinPoint.getArgs());
    38.         // 尝试从缓存获取
    39.         String cachedValue = redisTemplate.opsForValue().get(key);
    40.         if (StringUtils.isNotBlank(cachedValue)) {
    41.             Type returnType = ((MethodSignature) joinPoint.getSignature()).getReturnType();
    42.             return JSON.parseObject(cachedValue, returnType);
    43.         }
    44.         // 执行原方法
    45.         Object result = joinPoint.proceed();
    46.         // 处理缓存存储
    47.         if (result != null || redisCache.cacheNull()) {
    48.             String valueToCache = result != null ?
    49.                     JSON.toJSONString(result) :
    50.                     (redisCache.cacheNull() ? "[]" : null);

    51.             if (valueToCache != null) {
    52.                 redisTemplate.opsForValue().set(
    53.                         key,
    54.                         valueToCache,
    55.                         redisCache.expire(),
    56.                         redisCache.timeUnit()
    57.                 );
    58.             }
    59.         }
    60.         return result;
    61.     }

    62.     private String parseKey(String keyTemplate, Method method, Object[] args) {
    63.         String[] paramNames = parameterNameDiscoverer.getParameterNames(method);
    64.         EvaluationContext context = new StandardEvaluationContext();
    65.         if (paramNames != null) {
    66.             for (int i = 0; i < paramNames.length; i++) {
    67.                 context.setVariable(paramNames[i], args[i]);
    68.             }
    69.         }
    70.         return parser.parseExpression(keyTemplate).getValue(context, String.class);
    71.     }
    72. }
    复制代码
    代码片段示例
    1. @RedisCache(
    2.             key = "'category:homeSecond:' + #categoryType",  //缓存的Key + 动态参数
    3.             expire = 1, //过期时间
    4.             timeUnit = TimeUnit.DAYS // 时间单位
    5.     )
    6.     @Override
    7.     public ReturnVO<List<GoodsCategory>> listHomeSecondGoodsCategory(Integer level, Integer categoryType) {
    8.         // 数据库查询
    9.         List<GoodsCategory> dbList = goodsCategoryMapper.selectList(
    10.                 new LambdaQueryWrapper<GoodsCategory>()
    11.                         .eq(GoodsCategory::getCategoryLevel, level)
    12.                         .eq(GoodsCategory::getCategoryType, categoryType)
    13.                         .eq(GoodsCategory::getIsHomePage, 1)
    14.                         .orderByDesc(GoodsCategory::getHomeSort)
    15.         );
    16.         // 设置父级UUID(可优化为批量查询)
    17.         List<Long> parentIds = dbList.stream().map(GoodsCategory::getParentId).distinct().collect(Collectors.toList());
    18.         Map<Long, String> parentMap = goodsCategoryMapper.selectBatchIds(parentIds)
    19.                 .stream()
    20.                 .collect(Collectors.toMap(GoodsCategory::getId, GoodsCategory::getUuid));

    21.         dbList.forEach(item -> item.setParentUuid(parentMap.get(item.getParentId())));
    22.         return ReturnVO.ok("列出首页二级分类", dbList);
    23.     }
    复制代码
    最终效果:

    到此这篇关于Redis+自定义注解+AOP实现声明式注解缓存查询的示例的文章就介绍到这了,更多相关Redis 声明式注解缓存查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:https://www.jb51.net/database/338869uoe.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?立即注册

    ×

    最新评论

    浏览过的版块

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表