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

最后修改: 2022年 10月 12日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

在本教程中,我们为一些基本的真实世界的例子做缓存。值得注意的是,我们将演示如何将这种缓存机制配置为有时间限制的。我们也把这种时间限制称为缓存的生存时间(TTL)。

2. Configuration for Spring Caching

2.为Spring缓存配置

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.

之前,我们已经演示了如何使用Spring的@Cacheable注解。同时,缓存的一个实际用例是当酒店预订网站的主页面被频繁打开时。这意味着提供酒店列表的REST端点经常被请求,从而频繁调用数据库。与直接从内存中提供数据相比,数据库调用的速度较慢。

First, we’ll create SpringCachingConfig:

首先,我们将创建SpringCachingConfig

@Configuration
@EnableCaching
public class SpringCachingConfig {

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

We also need SpringCacheCustomizer:

我们还需要SpringCacheCustomizer

@Component
public class SpringCacheCustomizer implements CacheManagerCustomizer<ConcurrentMapCacheManager> {

    @Override
    public void customize(ConcurrentMapCacheManager cacheManager) {
        cacheManager.setCacheNames(asList("hotels"));
    }
}

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:

设置完成后,我们就可以利用Spring配置了。我们可以通过在内存中存储Hotel对象来减少REST端点的响应时间。我们使用@Cacheable注解来缓存Hotel对象的列表,如下面的代码片段。

@Cacheable("hotels")
public List<Hotel> getAllHotels() {
    return hotelRepository.getAllHotels();
}

4. Setting TLL for @Cacheable

4.为@Cacheable设置TLL

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.

然而,缓存的Hotels列表可能会因为更新、删除或添加而在数据库中发生变化。我们希望通过设置一个生存时间间隔(TTL)来刷新缓存,之后在第一次调用上文第3节中的方法时,删除现有的缓存条目并重新填充。

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注解来做到这一点。例如,在下面的例子中,我们通过caching.spring.hotelListTTL变量设置TTL。

@CacheEvict(value = "hotels", allEntries = true)
@Scheduled(fixedRateString = "${caching.spring.hotelListTTL}")
public void emptyHotelsCache() {
    logger.info("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。

caching.spring.hotelListTTL=43200000

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

另外,如果我们使用的是基于YAML的设计,我们可以将其设置为。

caching:
  spring:
    hotelListTTL: 43200000

5. Conclusion

5.总结

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.

在这篇文章中,我们探讨了如何为基于Spring的缓存设置TTL缓存。一如既往,我们可以在GitHub上找到完整的代码