springboot 使用注解设置缓存时效

springboot 使用注解设置缓存时效

bash 复制代码
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;

public class CustomRedisCacheManager extends RedisCacheManager {

    /*
     * @description 提供默认构造器
     * @author xianping
     * @date 2020/9/28 9:22
     * @param
     * @param cacheWriter
     * @param defaultCacheConfiguration
     * @return
     **/
    public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /*
     * @description 重写父类createRedisCache方法
     * @author xianping
     * @date 2020/9/28 9:22
     * @param
     * @param name @Cacheable中的value
     * @param cacheConfig
     * @return org.springframework.data.redis.cache.RedisCache
     **/
    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        //名称中存在#标记进行到期时间配置
        if (!name.isEmpty() && name.contains("#")) {
            String[] SPEL = name.split("#");

            if (StringUtils.isNumeric(SPEL[1])) {
                //配置缓存到期时间
                int cycle = Integer.parseInt(SPEL[1]);
                return super.createRedisCache(SPEL[0], cacheConfig.entryTtl(Duration.ofMinutes(cycle * 24 * 60)));
            }
        }
        return super.createRedisCache(name, cacheConfig);
    }
}
bash 复制代码
 @PostMapping("/getVehicleMap")
    @Cacheable(value = "getVehicle#1")
    @Operation(summary = "交通工具类型获取")
    public R<JSONArray> getVehicleMap() {
相关推荐
你的人类朋友23 分钟前
什么是断言?
前端·后端·安全
程序员小凯1 小时前
Spring Boot缓存机制详解
spring boot·后端·缓存
i学长的猫2 小时前
Ruby on Rails 从0 开始入门到进阶到高级 - 10分钟速通版
后端·ruby on rails·ruby
用户21411832636022 小时前
别再为 Claude 付费!Codex + 免费模型 + cc-switch,多场景 AI 编程全搞定
后端
茯苓gao2 小时前
Django网站开发记录(一)配置Mniconda,Python虚拟环境,配置Django
后端·python·django
Cherry Zack3 小时前
Django视图进阶:快捷函数、装饰器与请求响应
后端·python·django
程序媛徐师姐3 小时前
Java基于SpringBoot的茶叶商城系统,附源码+文档说明
java·spring boot·java springboot·茶叶商城系统·java茶叶商城系统·茶叶·java茶叶商城
爱读源码的大都督3 小时前
为什么有了HTTP,还需要gPRC?
java·后端·架构
码事漫谈3 小时前
致软件新手的第一个项目指南:阶段、文档与破局之道
后端
间彧3 小时前
Spring Boot条件注解详解与项目实战
后端