Cache Eviction in Spring Boot – Spring Boot中的缓存驱逐

最后修改: 2018年 10月 8日

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

1. Overview

1.概述

In this quick tutorial, we’ll learn how to perform cache eviction using Spring. To demonstrate this, we’ll create a small example.

在这个快速教程中,我们将学习如何使用Spring执行缓存驱逐。为了证明这一点,我们将创建一个小例子。

Before proceeding, check out our article, Guide To Caching in Spring, to get familiar with how Spring caching works.

在继续之前,请查看我们的文章,Guide To Caching in Spring,以熟悉Spring缓存的工作方式。

2. How to Evict a Cache?

2.如何驱逐缓存? 2.如何驱逐缓存?

Spring provides two ways to evict a cache, either by using the @CacheEvict annotation on a method, or by auto-wiring the CacheManger and clearing it by calling the clear() method.

Spring提供了两种方法来驱逐缓存,一种是在方法上使用@CacheEvict注解,另一种是自动连接CacheManger并通过调用clear()方法来清除它。

Here’s how we can implement these two cache eviction mechanisms in code.

下面是我们如何在代码中实现这两种缓存驱逐机制。

2.1. Using @CacheEvict

2.1.使用@CacheEvict

Let’s create an empty method with the @CacheEvict annotation, and provide the cache name that we want to clear as an argument of the annotation. In this case, we want to clear the cache with the name “first”:

让我们创建一个带有@CacheEvict注解的空方法,并提供我们想要清除的缓存名称作为注解的参数。在这个例子中,我们想清除名字为 “first “的缓存。

@CacheEvict(value = "first", allEntries = true)
public void evictAllCacheValues() {}

Spring will intercept all the methods annotated with @CacheEvict and clear all the values based on the allEntries flag.

Spring将拦截所有用@CacheEvict注释的方法,并根据allEntries标志清除所有值

It’s also possible to evict values based on a particular key. For this, all we have to do is pass the cache key as an argument to the annotation, instead of the allEntries flag:

也可以根据一个特定的键来驱逐值。为此,我们所要做的就是将缓存键作为参数传递给注解,而不是allEntries标志。

@CacheEvict(value = "first", key = "#cacheKey")
public void evictSingleCacheValue(String cacheKey) {}

Since the value of the key attribute is dynamic, we can either use Spring Expression Language, or a custom key generator by implementing KeyGenerator to pick the arguments of interest or the nested properties.

由于key属性的值是动态的,我们可以使用Spring表达式语言,或者通过实现KeyGenerator自定义密钥生成器来挑选感兴趣的参数或嵌套属性。

2.2. Using CacheManager

2.2.使用CacheManager

Next, let’s look at how we can evict the cache using the CacheManager provided by the Spring Cache module. First, we have to auto-wire the implemented CacheManager bean.

接下来,让我们看看如何使用Spring Cache模块提供的CacheManager来驱逐缓存。首先,我们必须自动连接已实现的CacheManager Bean。

Then we can clear the caches with it based on our needs:

然后我们可以根据我们的需要用它来清除缓存。

@Autowired
CacheManager cacheManager;

public void evictSingleCacheValue(String cacheName, String cacheKey) {
    cacheManager.getCache(cacheName).evict(cacheKey);
}

public void evictAllCacheValues(String cacheName) {
    cacheManager.getCache(cacheName).clear();
}

As we can see in the code, the clear() method will clear all the cache entries, and the evict() method will clear values based on a key.

正如我们在代码中看到的,clear()方法将清除所有的缓存条目,而evict()方法将根据一个键来清除值

3. How to Evict All Caches?

3.如何驱逐所有缓存?

Spring doesn’t provide an out of the box functionality to clear all the caches, but we can achieve this easily by using the getCacheNames() method of the cache manager.

Spring并没有提供一个开箱即用的功能来清除所有的缓存,但是我们可以通过使用缓存管理器的getCacheNames()方法来轻松实现。

3.1. Eviction on Demand

3.1.按需驱逐

Now let’s see how we can clear all the caches on demand. In order to create a trigger point, we have to expose an endpoint first:

现在让我们看看如何按需清除所有的缓存。为了创建一个触发点,我们必须首先暴露一个端点。

@RestController
public class CachingController {
	
    @Autowired
    CachingService cachingService;
	
    @GetMapping("clearAllCaches")
    public void clearAllCaches() {
        cachingService.evictAllCaches();
    }
}

In the CachingService, we can then clear all the caches by iterating over the cache names obtained from the cache manager:

CachingService中,我们可以通过迭代从缓存管理器获得的缓存名称来清除所有缓存

public void evictAllCaches() {
    cacheManager.getCacheNames().stream()
      .forEach(cacheName -> cacheManager.getCache(cacheName).clear());
}

3.2. Automatic Eviction

3.2.自动驱逐

There are certain use cases where cache eviction should be performed automatically at certain intervals. In this case, we can make use of the Spring’s task scheduler:

在某些用例中,缓存的驱逐应该在一定的时间间隔内自动执行。在这种情况下,我们可以利用Spring的任务调度器

@Scheduled(fixedRate = 6000)
public void evictAllcachesAtIntervals() {
    evictAllCaches();
}

4. Conclusion

4.结论

In this article, we learned how to evict caches in different ways. One of the things worth noting about these mechanisms is that it’ll work with all of the various cache implementations, like eh-cache, infini-span, apache-ignite etc.

在这篇文章中,我们学习了如何用不同的方式来驱逐缓存。这些机制中值得注意的一点是,它可以与所有不同的缓存实现一起工作,比如eh-cache、infini-span、apache-ignite等等。

As always, all the examples mentioned in this article can be found over on Github.

一如既往,本文中提到的所有例子都可以在Github上找到over