知識庫 / Spring / Spring Boot RSS 訂閱

Spring Boot 與 Caffeine 緩存

Spring Boot
HongKong
6
12:53 PM · Dec 06 ,2025

1. 概述

Caffeine 緩存是一個高性能的 Java 緩存庫。 在本簡短的教程中,我們將學習如何使用它與 Spring Boot 結合使用。

2. 依賴項

要開始使用 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>

這些導入了 Spring 的基本緩存支持,以及 Caffeine 庫。

3. 配置

現在我們需要配置我們 Spring Boot 應用程序中的緩存。

首先,我們創建一個 Caffeine Bean。 這主要配置將控制緩存行為,例如過期時間、緩存大小限制等

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

接下來,我們需要使用 Spring 的 CacheManager 接口創建一個新的 Bean。 Caffeine 提供了該接口的實現,需要我們之前創建的 Caffeine 對象:

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

最後,我們需要使用 Spring Boot 中的 @EnableCaching 註解啓用緩存。可以將該註解添加到應用程序中的任何 @Configuration 類中。

4. 示例

啓用緩存並配置使用 Caffeine 時,讓我們看看如何在我們的 Spring Boot 應用程序中使用緩存的一些示例。

在 Spring Boot 中使用緩存的主要方式是使用 @Cacheable 註解。 此註解適用於任何 Spring Bean 的方法(甚至整個類)。 它指示註冊的緩存管理器將方法調用的結果存儲在緩存中。

典型的用法是在服務類中:

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

使用帶有參數的 @Cacheable 註解將強制 Spring 使用默認的緩存名稱和緩存鍵。

通過向註解添加參數,我們可以覆蓋這兩個行為。

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

上面的示例告訴 Spring 使用名為 address_cache 的緩存,以及緩存鍵的 customerId 參數。

最後,由於緩存管理器本身也是一個 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. 結論

在本教程中,我們學習瞭如何配置 Spring Boot 使用 Caffeine 緩存,並提供了使用緩存的應用程序示例。

發佈 評論

Some HTML is okay.