Setting Time-To-Live Value for Caching – 为缓存设置生存时间值

最后修改: 2022年 10月 12日

1. Overview


In this tutorial, we do caching for some basic real-world examples. Notably, we’ll demonstrate how we can configure this caching mechanism to be time-limited. We also refer to such time-limitation as time-to-live (TTL) for a cache.


2. Configuration for Spring Caching


Previously, we have demonstrated how we can use @Cacheable annotation from Spring. Meanwhile, a practical use case for caching is when a Hotel booking website’s main page is opened frequently. This means that the REST endpoint for providing a list of Hotels is requested often, making frequent calls to the database. Database calls are slower as compared to providing data directly from memory.


First, we’ll create SpringCachingConfig:


public class SpringCachingConfig {

    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("hotels");

We also need SpringCacheCustomizer:


public class SpringCacheCustomizer implements CacheManagerCustomizer<ConcurrentMapCacheManager> {

    public void customize(ConcurrentMapCacheManager cacheManager) {

3. @Cacheable Caching

3.@Cacheable 缓存

After setup, we are able to make use of Spring configuration. We can reduce the REST endpoint response time by storing the Hotel objects in memory. We use the @Cacheable annotation for caching a list of Hotel objects as in the code snippet below:


public List<Hotel> getAllHotels() {
    return hotelRepository.getAllHotels();

4. Setting TLL for @Cacheable


However, the cached Hotels list may change in the database over time due to updates, deletions, or additions. We want to refresh the cache by setting a time-to-live interval (TTL), after which the existing cache entries are removed and refilled upon the first call of the method in Section 3 above.


We can do this by making use of @CacheEvict annotation. For instance, in the example below, we set the TTL through caching.spring.hotelListTTL variable:


@CacheEvict(value = "hotels", allEntries = true)
@Scheduled(fixedRateString = "${caching.spring.hotelListTTL}")
public void emptyHotelsCache() {"emptying Hotels cache");

We want the TTL to be 12 hours. The value in terms of milliseconds turns out to be 12 x 3600 x 1000 = 43200000. We define this in environment properties. Additionally, if we are using a properties-based environment configuration, we can set the cache TTL as follows:

我们希望TTL是12小时。以毫秒为单位的值变成了12 x 3600 x 1000 = 43200000。我们在环境属性中定义这个。此外,如果我们使用的是基于属性的环境配置,我们可以按如下方式设置缓存TTL。


Alternatively, if we are using a YAML-based design, we can set it as:


    hotelListTTL: 43200000

5. Conclusion


In this article, we explored how to set TTL caching for Spring-based caching. As always, we can find the complete code over on GitHub.