posts - 146,comments - 15,views - 13万
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 *  方法缓存注解
 *
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodCache {
  /**
   * redisKey 的一部分 最终的 rediskey是 appId + subAppId + key + (方法对应的参数)
   *
   */
   String key();
 
   /**
    *  缓存时间 单位为秒
    */
    int expireTime() default 3600;
}
 
@Sl4j
@Aspect
@Component
public class MethodCacheAspect {
     @Resource
     private RedisTemplate<String, String> redisTemplate;
 
     @Value("${application.appId}")
     private String appId;
      
     @Value("${application.subAppId}")
     private String subAppId;
 
     @Pointcut(value = "@annotation(com.fengye.it.utils.annotations.MethodCache)")
     public Object doAround(ProceedingJoinPointjoinPoint, MethodCache methodCache) throws Throwable {
         log.info("MethodCacheAspect doAround start==>);
         // 构造KEY appId + subAppId + key + (方法对应的参数)
         StringBuilder sb = new StringBuilder(appId);
         sb.append(subAppId).append(methodCache.key());
         Object[] args = joinPoint.getArgs();
         if (args != null && args.length !=0) {
            for (Object arg : args) {
                sb.append(arg.toString());
            }
         }
         String redisKey = sb.toString();
         log.info("MethodCacheAspect doAround redisKey==>:{}", redisKey);
 
         // 获取缓存 没有则新增
         String value = redisTemplate.opsForValue().get(redisKey);
         if (value == null) {
             // 没有缓存 则执行方法
             Object proceed = joinPoint.proceed();
             String jsonString = JSONObject.toJSONString(proceed, SerializerFeature.WriteMapNullValue);
             // 并保存到redis
             redisTemplate.opsForValue().set(redisKey, jsonString, methodCache.expireTime(), TimeUnit.SECONDS);
             return proceed;
         }
         // 获取目标方法对应返回值的class对象
         Signature signature = joinPoint.getSignature();
         if (signature instanceof MethodSignature) {
             Class returnType = ((MethodSignature) signature).getReturnType();
             return JSONObject.parseObject(value).toJavaObject(returnType);
         }
         log.error("MethodCacheAspect doAround signature is not MethodSignature redisKey==>:{}", redisKey);
         return joinPoint.proceed();
     }
}       

  

posted on   人无名,则可专心练剑  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2020-06-17 SQL Server2008安装教程
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示