如何在 Spring Boot 中为 @Cacheable 设置过期时间?

How to set expiration for @Cacheable in Spring Boot?

我在 Spring 引导应用程序中有以下缓存实现,它运行没有任何问题。但是,我想为这种方法定义过期时间。是否可以为 @Cacheable 设置过期时间?

我查看了 Expiry time @Cacheable spring boot@Cacheable 似乎没有直接的方法。有可能通过聪明的方法吗?

@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager();
    }
}
@Component
public class SimpleCacheCustomizer 
  implements CacheManagerCustomizer<ConcurrentMapCacheManager> {

    @Override
    public void customize(ConcurrentMapCacheManager cacheManager) {
        cacheManager.setCacheNames(asList("users"));
    }
}
@Cacheable("users")
public List<User> getUsers(UUID id) {...}

Spring documentation所述,Spring的默认缓存系统没有TTL。

8.7. How can I Set the TTL/TTI/Eviction policy/XXX feature?

Directly through your cache provider. The cache abstraction is an abstraction, not a cache implementation. The solution you use might support various data policies and different topologies that other solutions do not support (for example, the JDK ConcurrentHashMap — exposing that in the cache abstraction would be useless because there would no backing support). Such functionality should be controlled directly through the backing cache (when configuring it) or through its native API

如果您想要 TTL 配置,则必须使用其他缓存提供程序,例如 RedisGemfire

如何使用 TTLRedis 的示例可用