Commit 47698bfc6c1d71d1e628595762e1984d10354c9c

Authored by jlc@yoc.tech
1 parent 72d2dcc6

feat: 拓展 支持自定义过期时间的 RedisCacheManager 使支持自定义过期时间单位

yudao-framework/yudao-spring-boot-starter-redis/src/main/java/cn/iocoder/yudao/framework/redis/core/TimeoutRedisCacheManager.java
1 package cn.iocoder.yudao.framework.redis.core; 1 package cn.iocoder.yudao.framework.redis.core;
2 2
  3 +import cn.hutool.core.util.NumberUtil;
3 import cn.hutool.core.util.StrUtil; 4 import cn.hutool.core.util.StrUtil;
4 import org.springframework.boot.convert.DurationStyle; 5 import org.springframework.boot.convert.DurationStyle;
5 import org.springframework.cache.annotation.Cacheable; 6 import org.springframework.cache.annotation.Cacheable;
@@ -13,8 +14,8 @@ import java.time.temporal.ChronoUnit; @@ -13,8 +14,8 @@ import java.time.temporal.ChronoUnit;
13 14
14 /** 15 /**
15 * 支持自定义过期时间的 {@link RedisCacheManager} 实现类 16 * 支持自定义过期时间的 {@link RedisCacheManager} 实现类
16 - *  
17 - * 在 {@link Cacheable#cacheNames()} 格式为 "key#ttl" 时,# 后面的 ttl 为过期时间,单位为秒 17 + * <p>
  18 + * 在 {@link Cacheable#cacheNames()} 格式为 "key#ttl" 时,# 后面的 ttl 为过期时间,单位为最后一个字母(支持的单位有:d天,h小时,m分钟,s秒),默认单位为秒
18 * 19 *
19 * @author 芋道源码 20 * @author 芋道源码
20 */ 21 */
@@ -42,10 +43,41 @@ public class TimeoutRedisCacheManager extends RedisCacheManager { @@ -42,10 +43,41 @@ public class TimeoutRedisCacheManager extends RedisCacheManager {
42 // 移除 # 后面的 : 以及后面的内容,避免影响解析 43 // 移除 # 后面的 : 以及后面的内容,避免影响解析
43 names[1] = StrUtil.subBefore(names[1], StrUtil.COLON, false); 44 names[1] = StrUtil.subBefore(names[1], StrUtil.COLON, false);
44 // 解析时间 45 // 解析时间
45 - Duration duration = DurationStyle.detectAndParse(names[1], ChronoUnit.SECONDS); 46 + Duration duration = parseDuration(names[1]);
46 cacheConfig = cacheConfig.entryTtl(duration); 47 cacheConfig = cacheConfig.entryTtl(duration);
47 } 48 }
48 return super.createRedisCache(names[0], cacheConfig); 49 return super.createRedisCache(names[0], cacheConfig);
49 } 50 }
50 51
  52 + /**
  53 + * 解析 Duration
  54 + *
  55 + * @param ttlStr
  56 + * @return
  57 + */
  58 + private Duration parseDuration(String ttlStr) {
  59 + String timeUnit = StrUtil.subSuf(ttlStr, -1);
  60 + switch (timeUnit) {
  61 + case "d":
  62 + return Duration.ofDays(removeSuffix(ttlStr));
  63 + case "h":
  64 + return Duration.ofHours(removeSuffix(ttlStr));
  65 + case "m":
  66 + return Duration.ofMinutes(removeSuffix(ttlStr));
  67 + case "s":
  68 + return Duration.ofSeconds(removeSuffix(ttlStr));
  69 + default:
  70 + return Duration.ofSeconds(Long.parseLong(ttlStr));
  71 + }
  72 + }
  73 +
  74 + /**
  75 + * 移除多余的后缀
  76 + *
  77 + * @param ttlStr
  78 + * @return
  79 + */
  80 + private Long removeSuffix(String ttlStr) {
  81 + return NumberUtil.parseLong(StrUtil.sub(ttlStr, 0, ttlStr.length() - 1));
  82 + }
51 } 83 }