【问题标题】:Redis: Set different time to live for methods annotated with @CacheableRedis:为使用 @Cacheable 注释的方法设置不同的生存时间
【发布时间】:2019-10-27 02:29:33
【问题描述】:

我有一组看起来有点像这样的缓存方法:

@Cacheable(value = "myCacheName", keyGenerator = "myKeyGenerator")
public Product getProduct(ProductRequest request) {
    // ...
}

而且我需要为这些方法返回的对象设置不同的生存时间(过期间隔)。

问题: 根据the documentation,提供的方法是在方法的返回类型上使用@RedisHash(timeToLive=…​)@TimeToLive 注释。但是,我不想用缓存相关的逻辑污染我的域类。此外,我的一些方法返回了我无法修改的类的字符串或对象。我宁愿以更可配置的方式实现它。还有一个名为 spring.cache.redis.time-to-live 的配置属性,但它在所有地方应用相同的生存时间。

问题:有没有办法在方法级别指定生存时间/到期间隔?或者一般来说,如何以更优雅的方式实现它?

【问题讨论】:

  • 如果缓存名称有限,可以通过配置CacheManager bean为每个缓存名称设置TTL。如果 SDR 允许将 TTL 配置为 @Cacheable 的属性,那就太好了
  • @MạnhQuyếtNguyễn 我的缓存名称确实有限。能否请您详细说明解决方案。
  • @OleksandrShpota 你可以看看this。这个想法是为不同的缓存管理器配置不同的 TTL。

标签: java spring spring-boot redis spring-data-redis


【解决方案1】:

您好,如果您只想使用 Spring 注释,一种方法如下。 @CacheConfig annotation 允许您定义特定的 CacheManager 以进一步使用 @Cacheable annotation 还允许定义 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")

【讨论】:

  • RedisCacheManager 没有 setDefaultExpiration 方法!我正在使用弹簧数据 redis 2.5.7
猜你喜欢
  • 2021-06-08
  • 2018-12-05
  • 1970-01-01
  • 2018-05-06
  • 2013-06-26
  • 1970-01-01
  • 2012-08-01
  • 2021-10-12
  • 1970-01-01
相关资源
最近更新 更多