java 使用Caffeine实现本地缓存
Caffeine 是一个高性能的本地缓存库,广泛用于 Java 应用程序中。它支持多种缓存淘汰策略(如基于容量、时间、引用等),并且性能优于 Guava Cache,因此成为许多开发者的首选。
以下是一个完整的 Caffeine 本地缓存实例的实现:
1. 添加依赖
如果你使用 Maven 构建项目,请在 pom.xml 中添加以下依赖:
<dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId><version>3.1.8</version> <!-- 版本号可以根据需要更新 -->
</dependency>
2. 示例代码
以下是一个完整的示例,展示如何使用 Caffeine 创建和使用本地缓存。
(1) 基本缓存操作
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;import java.util.concurrent.TimeUnit;public class CaffeineCacheExample {public static void main(String[] args) throws InterruptedException {// 创建缓存实例Cache<String, String> cache = Caffeine.newBuilder().maximumSize(100) // 设置最大容量为 100.expireAfterWrite(1, TimeUnit.MINUTES) // 写入后 1 分钟过期.build();// 向缓存中添加数据cache.put("key1", "value1");cache.put("key2", "value2");// 获取缓存中的值System.out.println("key1: " + cache.getIfPresent("key1")); // 输出: value1System.out.println("key3: " + cache.getIfPresent("key3")); // 输出: null// 模拟过期Thread.sleep(65000); // 等待 65 秒(超过 1 分钟)System.out.println("key1 after expiration: " + cache.getIfPresent("key1")); // 输出: null}
}
(2) 使用加载函数
Caffeine 支持在缓存未命中时自动加载数据。可以通过 CacheLoader 或 LoadingCache 实现。
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;import java.util.concurrent.TimeUnit;public class CaffeineLoadingCacheExample {public static void main(String[] args) {// 创建 LoadingCache 实例LoadingCache<String, String> cache = Caffeine.newBuilder().maximumSize(100) // 设置最大容量为 100.expireAfterWrite(10, TimeUnit.MINUTES) // 写入后 10 分钟过期.build(new CacheLoader<>() {@Overridepublic String load(String key) {return "Default Value for " + key; // 缓存未命中时加载默认值}});// 获取缓存中的值(如果不存在则调用 load 方法)System.out.println(cache.get("key1")); // 输出: Default Value for key1System.out.println(cache.get("key2")); // 输出: Default Value for key2// 手动放入值cache.put("key1", "Custom Value for key1");System.out.println(cache.get("key1")); // 输出: Custom Value for key1}
}
(3) 异步加载缓存
Caffeine 支持异步加载缓存,适合耗时的数据加载场景。
import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.Caffeine;import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;public class CaffeineAsyncCacheExample {public static void main(String[] args) {// 创建异步缓存实例AsyncCache<String, String> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(10, TimeUnit.MINUTES).buildAsync((key, executor) -> {// 模拟异步加载数据return CompletableFuture.supplyAsync(() -> "Async Value for " + key);});// 异步获取缓存值cache.get("key1").thenAccept(value -> {System.out.println("key1: " + value); // 输出: Async Value for key1});}
}
(4) 统计功能
Caffeine 提供了丰富的统计功能,可以帮助你监控缓存的命中率、加载时间等。
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;public class CaffeineStatsExample {public static void main(String[] args) {// 创建带有统计功能的缓存Cache<String, String> cache = Caffeine.newBuilder().maximumSize(100).recordStats() // 开启统计功能.build();// 添加数据cache.put("key1", "value1");// 查询数据cache.getIfPresent("key1"); // 命中cache.getIfPresent("key2"); // 未命中// 打印统计信息var stats = cache.stats();System.out.println("Hit Count: " + stats.hitCount()); // 输出: 1System.out.println("Miss Count: " + stats.missCount()); // 输出: 1}
}
3. 常见配置选项
4. 总结
- 优点:
- 高性能,适合高并发场景。
- 功能丰富,支持多种淘汰策略和加载方式。
- 易于集成 Spring Cache。
- 适用场景:
- 数据频繁读取但不经常变化的场景。
- 需要快速响应的本地缓存需求。