gpt4 book ai didi

spring-boot - springboot2.0中使用@cacheable时如何为每个redis缓存配置不同的ttl

转载 作者:IT王子 更新时间:2023-10-29 06:03:03 25 4
gpt4 key购买 nike

我在 springboot2.0 中使用 @cacheable 和 redis。我已将 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;
}

但是这使得所有键的 ttl 都是 30 秒,如何为具有不同缓存名称的每个 redis 缓存配置不同的 ttl?

最佳答案

您可以仅使用一个 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);
}

关于spring-boot - springboot2.0中使用@cacheable时如何为每个redis缓存配置不同的ttl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51054774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com