在springboot2.0中使用@cacheable时如何为每个Redis缓存配置不同的ttl

C.y*_*sof 2 caching redis spring-boot

我在带有Redis的springboot2.0中使用@cacheable。我已将RedisCacheManager配置如下:

@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {

    RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
    SerializationPair<Object> valueSerializationPair = RedisSerializationContext.SerializationPair
            .fromSerializer(new GenericJackson2JsonRedisSerializer());
    RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
    cacheConfiguration = cacheConfiguration.serializeValuesWith(valueSerializationPair);
    cacheConfiguration = cacheConfiguration.prefixKeysWith("myPrefix");
    cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30));

    RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter, cacheConfiguration);
    return redisCacheManager;
}
Run Code Online (Sandbox Code Playgroud)

但这使所有密钥的ttl变为30秒,如何为每个具有不同缓存名称的redis缓存配置不同的ttl?

小智 10

您可以通过为每个缓存创建不同的配置,然后将它们放置在用于创建CacheManager的映射中,从而仅使用一个CacheManager为每个缓存配置不同的到期时间。

例如:

@Bean
RedisCacheWriter redisCacheWriter() {
    return RedisCacheWriter.lockingRedisCacheWriter(jedisConnectionFactory());
}

@Bean
RedisCacheConfiguration defaultRedisCacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(defaultCacheExpiration));
}

@Bean
CacheManager cacheManager() {
    Map<String, RedisCacheConfiguration> cacheNamesConfigurationMap = new HashMap<>();
    cacheNamesConfigurationMap.put("cacheName1", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(ttl1)));
    cacheNamesConfigurationMap.put("cacheName2", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(ttl2)));
    cacheNamesConfigurationMap.put("cacheName3", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(ttl3)));

    return new RedisCacheManager(redisCacheWriter(), defaultRedisCacheConfiguration(), cacheNamesConfigurationMap);
}
Run Code Online (Sandbox Code Playgroud)


C.y*_*sof 4

如果您在使用 @cacheable 时需要为缓存配置不同的过期时间,您可以为不同的 CacheManager 配置不同的 ttl,并在服务中使用缓存时指定 cacheManager。

 @Cacheable(cacheManager = "expireOneHour", value = "onehour", key = "'_onehour_'+#key", sync = true)
Run Code Online (Sandbox Code Playgroud)