我有一组看起来有点像这样的缓存方法:
@Cacheable(value = "myCacheName", keyGenerator = "myKeyGenerator")
public Product getProduct(ProductRequest request) {
// ...
}
而且我需要为这些方法返回的对象设置不同的生存时间(过期间隔)。
问题:根据the documentation ,提供的方法是在方法的返回类型上使用 @RedisHash(timeToLive=… )
或 @TimeToLive
注释。但是,我不想用缓存相关逻辑污染我的域类。此外,我的一些方法返回我无法修改的字符串或类对象。我更愿意以更可配置的方式实现它。还有一个名为 spring.cache.redis.time-to-live
的配置属性,但它在所有地方应用相同的生存时间。
问题:有没有办法在方法级别指定生存时间/过期时间间隔?或者一般来说,如何以更优雅的方式实现它?
最佳答案
您好,如果您只想使用 Spring 注释,一种方法如下。
@CacheConfig
注释允许您定义特定的 CacheManager 以进一步使用 @Cacheable
注释还允许定义 cacheManager
@CacheConfig(cacheNames="myCacheName",cacheManager="timeoutCacheManager")
class ProductReader {
@Cacheable(value = "myCacheName", keyGenerator = "myKeyGenerator")
public Product getProduct(ProductRequest request) {
// ...
}
}
@Bean
public CacheManager timeoutCacheManager(RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(mytimeToLive);
return cacheManager;
}
这也是一个更广泛的缓存配置的片段,它再次产生 CacheManager。这次它配置了多个区域:
@Bean (name="cacheManager")
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration conf_ready_info = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMillis(50000));
RedisCacheConfiguration conf_base_info = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMillis(60000));
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<String, RedisCacheConfiguration>();
cacheConfigurations.put("base_info", conf_base_info);
cacheConfigurations.put("ready_info", conf_ready_info);
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory)
.withInitialCacheConfigurations(cacheConfigurations).build();
}
最后一个例子来自: set expire key at specific time when using Spring caching with Redis
仅使用@Cacheable(value = "myCacheName", keyGenerator = "timeoutCacheManager")
关于java - Redis:为使用@Cacheable 注释的方法设置不同的生存时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56564503/