关于springboot:Springboot-注解-Cacheable自定义单个key设置expire超时时间-并在配置文件里配置

Springboot RedisCacheManager 类的配置 指定key的过期工夫 并在配置文件里配置

目标&成果

在springBoot中配置了RedisCache,当应用@Cacheable注解时,默认为redisCache,通过在配置文件里设置不同key的过期工夫,达到可自定义key过期工夫的成果。

计划

step 1

新建一个Map类,用于寄存要设置的key

@ConfigurationProperties
public class Properties {
 
    private final Map<String, Duration> initCaches = Maps.newHashMap();
 
    public Map<String, Duration> getInitCaches() {
        return initCaches;
    }
}

step2

在redis配置类里编写cacheManager,并将map set进去

@Autowired
private Properties properties;
 
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(10)).disableCachingNullValues();
 
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
 
    ImmutableSet.Builder<String> cacheNames = ImmutableSet.builder();
    ImmutableMap.Builder<String, RedisCacheConfiguration> cacheConfig = ImmutableMap.builder();
    for (Map.Entry<String, Duration> entry : properties.getInitCaches().entrySet()) {
        cacheNames.add(entry.getKey());
        cacheConfig.put(entry.getKey(), defaultCacheConfig.entryTtl(entry.getValue()));
    }
 
    return RedisCacheManager.builder(redisCacheWriter)
            .cacheDefaults(defaultCacheConfig)
            .initialCacheNames(cacheNames.build())
            .withInitialCacheConfigurations(cacheConfig.build())
            .build();
}
 

step3

在Springboot yml文件里配置相干的key的过期工夫 就能够指定@Cacheable的value的过期工夫

//伪代码
 
@Cacheable(cacheNames = "fooboo", key = "#xxx", unless = "#result == null")
public void fooboo(String xxx){}

applicaion.yml文件中设置

initCaches:
fooboo: 10m
fooboo1: 1h

则在redis缓存中fooboo的值,10分钟过期,fooboo1的值1小时过期

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理