mirror of
https://gitee.com/huangge1199_admin/vue-pro.git
synced 2024-11-22 23:31:52 +08:00
feat: 拓展 支持自定义过期时间的 RedisCacheManager 使支持自定义过期时间单位
This commit is contained in:
parent
72d2dcc68f
commit
47698bfc6c
@ -1,5 +1,6 @@
|
||||
package cn.iocoder.yudao.framework.redis.core;
|
||||
|
||||
import cn.hutool.core.util.NumberUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.springframework.boot.convert.DurationStyle;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
@ -13,8 +14,8 @@ import java.time.temporal.ChronoUnit;
|
||||
|
||||
/**
|
||||
* 支持自定义过期时间的 {@link RedisCacheManager} 实现类
|
||||
*
|
||||
* 在 {@link Cacheable#cacheNames()} 格式为 "key#ttl" 时,# 后面的 ttl 为过期时间,单位为秒
|
||||
* <p>
|
||||
* 在 {@link Cacheable#cacheNames()} 格式为 "key#ttl" 时,# 后面的 ttl 为过期时间,单位为最后一个字母(支持的单位有:d天,h小时,m分钟,s秒),默认单位为秒
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@ -42,10 +43,41 @@ public class TimeoutRedisCacheManager extends RedisCacheManager {
|
||||
// 移除 # 后面的 : 以及后面的内容,避免影响解析
|
||||
names[1] = StrUtil.subBefore(names[1], StrUtil.COLON, false);
|
||||
// 解析时间
|
||||
Duration duration = DurationStyle.detectAndParse(names[1], ChronoUnit.SECONDS);
|
||||
Duration duration = parseDuration(names[1]);
|
||||
cacheConfig = cacheConfig.entryTtl(duration);
|
||||
}
|
||||
return super.createRedisCache(names[0], cacheConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Duration
|
||||
*
|
||||
* @param ttlStr
|
||||
* @return
|
||||
*/
|
||||
private Duration parseDuration(String ttlStr) {
|
||||
String timeUnit = StrUtil.subSuf(ttlStr, -1);
|
||||
switch (timeUnit) {
|
||||
case "d":
|
||||
return Duration.ofDays(removeSuffix(ttlStr));
|
||||
case "h":
|
||||
return Duration.ofHours(removeSuffix(ttlStr));
|
||||
case "m":
|
||||
return Duration.ofMinutes(removeSuffix(ttlStr));
|
||||
case "s":
|
||||
return Duration.ofSeconds(removeSuffix(ttlStr));
|
||||
default:
|
||||
return Duration.ofSeconds(Long.parseLong(ttlStr));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除多余的后缀
|
||||
*
|
||||
* @param ttlStr
|
||||
* @return
|
||||
*/
|
||||
private Long removeSuffix(String ttlStr) {
|
||||
return NumberUtil.parseLong(StrUtil.sub(ttlStr, 0, ttlStr.length() - 1));
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user