在springboot2.0中使用@cacheable时如何为每个Redis缓存配置不同的ttl [英] how to configure different ttl for each redis cache when using @cacheable in springboot2.0
本文介绍了在springboot2.0中使用@cacheable时如何为每个Redis缓存配置不同的ttl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在带有redis的springboot2.0中使用@cacheable。我已将RedisCacheManager配置如下:
I am using @cacheable in springboot2.0 with redis. I have configured RedisCacheManager as follow:
@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秒,如何为每个密钥配置不同的ttl
but this make all key's ttl 30 second, how to configure different ttl for each redis cache with different cachename?
推荐答案
如果使用@cacheable时需要为缓存配置不同的过期时间,
可以使用不同的ttl配置不同的CacheManager,并在服务中使用缓存时指定cacheManager。
If you need configure different expire time for cache when using @cacheable , you can configure different CacheManager with different ttl,and specify cacheManager when using cache in your service.
@Cacheable(cacheManager = "expireOneHour", value = "onehour", key = "'_onehour_'+#key", sync = true)
这篇关于在springboot2.0中使用@cacheable时如何为每个Redis缓存配置不同的ttl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文