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

3次阅读

共计 1510 个字符,预计需要花费 4 分钟才能阅读完成。

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 小时过期

正文完
 0