Caffeine 是一個(gè)高性能的 Java 緩存庫(kù),常用于 Spring Boot 項(xiàng)目中。以下是如何在 Spring Boot 項(xiàng)目中集成和使用 Caffeine 的基本步驟:
1. 引入依賴
在你的 `pom.xml` 文件中添加以下依賴項(xiàng):
```xml
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
```
2. 配置緩存
在 `application.properties` 文件中配置 Caffeine 緩存:
```properties
spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=100,expireAfterWrite=10m
```
3. 啟用緩存
在 Spring Boot 主類上添加 `@EnableCaching` 注解:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CaffeineDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CaffeineDemoApplication.class, args);
}
}
```
4. 使用緩存
在需要緩存的方法上添加 `@Cacheable` 注解:
```java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class DataService {
@Cacheable(value = "data", key = "#id")
public String getData(Long id) {
// 模擬從數(shù)據(jù)庫(kù)獲取數(shù)據(jù)
return "Data for ID: " + id;
}
}
```
5. 運(yùn)行項(xiàng)目
啟動(dòng)你的 Spring Boot 應(yīng)用程序,緩存將自動(dòng)工作。