本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net
摘要:本文将介绍 Caffeine 缓存库,概述其背景、优点、缺点,并详细说明如何在 Java 项目中使用 Caffeine,以及如何将其与 Spring Boot 框架集成。最后,我们将通过一个简单的例子来演示 Caffeine 缓存的使用。
一、Caffeine 缓存背景
Caffeine 是一个高性能、可扩展的 Java 缓存库,由 Google 的 Ben Manes 开发。Caffeine 基于 ConcurrentHashMap 设计,采用了近似 LRU(Least Recently Used,最近最少使用)算法,以实现高速缓存淘汰策略。Caffeine 广泛应用于各类 Java 项目中,作为一种提高数据读取性能的优秀解决方案。
二、Caffeine 缓存优点与缺点
优点:
- 高性能:Caffeine 性能优于许多其他缓存库,因其采用了近似 LRU 算法,实现了高效的缓存淘汰策略。
- 灵活性:Caffeine 提供了丰富的配置选项,用户可根据项目需求灵活定制缓存策略。
- 易集成:Caffeine 可轻松与 Spring Boot 框架集成,实现便捷的缓存管理。
- 易于使用:Caffeine API 简洁易懂,便于开发者快速上手。
缺点:
- 仅支持 Java:Caffeine 为 Java 特有的缓存库,不能直接应用于其他编程语言。
- 近似 LRU 算法:虽然 Caffeine 采用了高效的近似 LRU 算法,但在某些场景下,其性能可能不如精确的 LRU 算法。
三、Caffeine 缓存基本使用方法
- 添加 Caffeine 依赖:
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.2</version>
</dependency>
- 创建 Caffeine 缓存实例:
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
Cache<String, Object> cache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
- 缓存操作:
// 添加缓存项
cache.put("key", "value");
// 获取缓存项
Object value = cache.getIfPresent("key");
// 删除缓存项
cache.invalidate("key");
四、Spring Boot 集成与配置
-
添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.9.2</version> </dependency> -
在 Spring Boot 主类上添加 @EnableCaching 注解:
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); } } -
在 application.properties 文件中配置 Caffeine 缓存:
spring.cache.type=caffeine spring.cache.caffeine.spec=maximumSize=100,expireAfterWrite=300s -
在需要使用缓存的方法上添加 @Cacheable 注解:
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class DataService { @Cacheable(value = "data", key = "#id") public Data getData(Long id) { // 模拟从数据库或其他来源获取数据 return new Data(id, "sample data"); } }五、示例
假设我们有一个简单的数据服务,需要根据 ID 从数据库中获取数据。为了提高性能,我们可以使用 Caffeine 缓存:
- 创建数据实体:
public class Data {
private Long id;
private String content;
public Data(Long id, String content) {
this.id = id;
this.content = content;
}
// 省略getter和setter方法
}
- 使用 Caffeine 缓存实现数据服务:
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@Service
public class DataService {
private final Cache<Long, Data> cache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
public Data getData(Long id) {
return cache.get(id, this::loadDataFromDatabase);
}
private Data loadDataFromDatabase(Long id) {
// 模拟从数据库获取数据
return new Data(id, "sample data");
}
}
当调用 getData 方法时,Caffeine 缓存会首先检查缓存中是否存在对应的数据,若存在则直接返回,否则从数据库中加载数据,并将其添加到缓存中。这样,我们就实现了一个简单的基于 Caffeine 的数据缓存服务。
Caffeine 还提供了许多其他功能,如:缓存回收策略、监听器、统计信息等。以下是一些补充内容:
六、Caffeine 缓存回收策略
Caffeine 提供了多种回收策略,可根据需求灵活配置:
- 基于大小的回收:
Cache<String, Object> cache = Caffeine.newBuilder()
.maximumSize(100)
.build();
- 基于权重的回收:
Cache<String, Object> cache = Caffeine.newBuilder()
.maximumWeight(1000)
.weigher((key, value) -> value.length())
.build();
- 基于时间的回收:
Cache<String, Object> cache = Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
七、Caffeine 缓存监听器
Caffeine 支持添加监听器,以便在缓存项被移除时执行特定操作:
Cache<String, Object> cache = Caffeine.newBuilder()
.maximumSize(100)
.removalListener((key, value, cause) -> {
System.out.println("Removed key: " + key + ", cause: " + cause);
})
.build();
八、Caffeine 缓存统计信息
Caffeine 提供了统计信息,方便查看缓存性能指标:
Cache<String, Object> cache = Caffeine.newBuilder()
.maximumSize(100)
.recordStats()
.build();
// 获取统计信息
com.github.benmanes.caffeine.cache.stats.CacheStats stats = cache.stats();