Search code examples
javaspringspring-bootcachingcache-expiration

How to set expiration for @Cacheable in Spring Boot?


I have the following cache implementation in a Spring Boot app and it is working without any problem. However, I want to define expiration for this approach. Is it possible to set expiration for @Cacheable?

I look at Expiry time @Cacheable spring boot and there is not seem to be a direct way for @Cacheable. Is it possible via a smart approach?

@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) {...}

Solution

  • As said in the Spring documentation, there is no TTL for the default cache system of Spring.

    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

    You'll have to use an other cache provider like Redis or Gemfire if you want a TTL configuration.

    An example of how to use TTL with Redis is available here.