Spring Boot and Caffeine Cache – Spring Boot和Caffeine Cache

最后修改: 2020年 6月 21日

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

1. Overview

1.概述

Caffeine cache is a high-performance cache library for Java. In this short tutorial, we’ll see how to use it with Spring Boot.

Caffeine 缓存是一个用于 Java 的高性能缓存库。在这个简短的教程中,我们将看到如何在Spring Boot中使用它。

2. Dependencies

2.依赖性

To get started with Caffeine and Spring Boot, we first add the spring-boot-starter-cache and caffeine dependencies:

要开始使用Caffeine和Spring Boot,我们首先要添加spring-boot-starter-cachecaffeine依赖项。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
    </dependency>
</dependencies>

These import the base Spring caching support, along with the Caffeine library.

这些都导入了基本的Spring缓存支持,以及Caffeine库。

3. Configuration

3.配置

Now we need to configure caching in our Spring Boot application.

现在我们需要在我们的Spring Boot应用程序中配置缓存。

First, we create a Caffeine bean. This is the main configuration that will control caching behavior such as expiration, cache size limits, and more:

首先,我们创建一个Caffeine bean。这是一个主要的配置,它将控制缓存行为,如过期、缓存大小限制等等

@Bean
public Caffeine caffeineConfig() {
    return Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES);
}

Next, we need to create another bean using the Spring CacheManager interface. Caffeine provides its implementation of this interface, which requires the Caffeine object we created above:

接下来,我们需要使用Spring的CacheManager接口创建另一个Bean。Caffeine提供了这个接口的实现,它需要我们上面创建的Caffeine对象。

@Bean
public CacheManager cacheManager(Caffeine caffeine) {
    CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
    caffeineCacheManager.setCaffeine(caffeine);
    return caffeineCacheManager;
}

Finally, we need to enable caching in Spring Boot using the @EnableCaching annotation. This can be added to any @Configuration class in the application.

最后,我们需要使用@EnableCaching注解来启用Spring Boot的缓存。这可以被添加到应用程序中的任何@Configuration类。

4. Examples

4.实例

With caching enabled and configured to use Caffeine, let’s look at a few examples of how we can use caching in our Spring Boot application.

在启用缓存并配置为使用Caffeine之后,让我们来看几个例子,看看我们如何在Spring Boot应用程序中使用缓存

The primary way to use caching in Spring Boot is with the @Cacheable annotation. This annotation works on any method of a Spring bean (or even the entire class). It instructs the registered cache manager to store the result of the method call in a cache.

在Spring Boot中使用缓存的主要方式是使用@Cacheable注解。这个注解适用于Spring Bean的任何方法(甚至是整个类)。它指示注册的缓存管理器将方法调用的结果存储在缓存中。

A typical usage is inside service classes:

一个典型的用法是在服务类内部。

@Service
public class AddressService {
    @Cacheable
    public AddressDTO getAddress(long customerId) {
        // lookup and return result
    }
}

Using the @Cacheable annotation without parameters will force Spring to use default names for both the cache and cache key.

使用不带参数的@Cacheable注解会迫使Spring对缓存和缓存键都使用默认名称。

We can override both of these behaviors by adding some parameters to the annotation:

我们可以通过向注释添加一些参数来覆盖这两种行为。

@Service
public class AddressService {
    @Cacheable(value = "address_cache", key = "customerId")
    public AddressDTO getAddress(long customerId) {
        // lookup and return result
    }
}

The example above tells Spring to use a cache named address_cache and the customerId argument for the cache key.

上面的例子告诉Spring使用一个名为address_cache的缓存和customerId参数作为缓存密钥。

Finally, because the cache manager is itself a Spring bean, we can also autowire it into any other bean and work with it directly:

最后,由于缓存管理器本身就是一个Spring Bean,我们也可以将其自动连接到任何其他Bean中,并直接使用它

@Service
public class AddressService {

    @Autowired
    CacheManager cacheManager;

    public AddressDTO getAddress(long customerId) {
        if(cacheManager.containsKey(customerId)) {
            return cacheManager.get(customerId);
        }
        
        // lookup address, cache result, and return it
    }
}

5. Conclusion

5.总结

In this tutorial, we’ve seen how to configure Spring Boot to use Caffeine cache, along with some examples of how to use caching in our application.

在本教程中,我们已经看到了如何配置Spring Boot以使用Caffeine缓存,以及一些如何在我们的应用程序中使用缓存的例子。

And of course, all of the code examples are located over on GitHub.

当然,所有的代码示例都位于GitHub上。