在 Java 应用的性能优化赛道上,缓存就像给频繁访问的数据加了个 "快捷通道",而Caffeine则是这条通道上的超级引擎。它凭借出色的性能和灵活的配置,成为 Java 领域缓存工具的佼佼者,让应用响应速度如虎添翼。

快速上手的基础缓存

想要使用 Caffeine,只需简单几步就能搭建起高效缓存:

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import java.util.concurrent.TimeUnit;public class CacheDemo {public static void main(String[] args) {// 构建缓存LoadingCache<String, String> cache = Caffeine.newBuilder().maximumSize(10_000) // 最大缓存数量.expireAfterWrite(5, TimeUnit.MINUTES) // 写入后5分钟过期.build(key -> loadDataFromDB(key)); // 缓存不存在时的加载函数// 读取缓存String value = cache.get("user123"); // 首次会调用loadDataFromDB加载String sameValue = cache.get("user123"); // 直接从缓存获取}// 模拟从数据库加载数据private static String loadDataFromDB(String key) {System.out.println("从数据库加载:" + key);return "数据-" + key;}
}

灵活的过期策略

Caffeine 支持多种过期策略,能根据业务需求精准控制缓存生命周期:

// 访问后过期:最后一次访问后30秒过期
LoadingCache<String, Object> accessExpireCache = Caffeine.newBuilder().expireAfterAccess(30, TimeUnit.SECONDS).build(key -> loadData(key));// 自定义过期时间:为每个键设置不同的过期时间
LoadingCache<String, Object> customExpireCache = Caffeine.newBuilder().expireAfter(new Expiry<String, Object>() {@Overridepublic long expireAfterCreate(String key, Object value, long currentTime) {// 不同的键设置不同的过期时间(单位:纳秒)return key.startsWith("temp_") ? 10_000_000_000L : 60_000_000_000L;}@Overridepublic long expireAfterUpdate(String key, Object value, long currentTime, long currentDuration) {return currentDuration; // 更新时不改变过期时间}@Overridepublic long expireAfterRead(String key, Object value, long currentTime, long currentDuration) {return currentDuration; // 读取时不改变过期时间}}).build(key -> loadData(key));

缓存移除的监听机制

当缓存被移除时,Caffeine 能及时通知你,方便做后续处理:

LoadingCache<String, String> removalListenerCache = Caffeine.newBuilder().maximumSize(100).removalListener((key, value, cause) -> {System.out.printf("键[%s]被移除,原因:%s%n", key, cause);// 可以在这里做资源清理等操作}).build(key -> loadData(key));

异步加载的非阻塞能力

为了不阻塞主线程,Caffeine 提供了异步加载的方式:

import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import java.util.concurrent.CompletableFuture;// 构建异步缓存
AsyncLoadingCache<String, String> asyncCache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).buildAsync(key -> loadDataAsync(key)); // 返回CompletableFuture// 异步获取缓存
CompletableFuture<String> future = asyncCache.get("user456");
future.thenAccept(value -> System.out.println("异步获取到值:" + value));

统计监控的贴心功能

Caffeine 还能记录缓存的使用情况,帮助你优化缓存策略:

LoadingCache<String, String> statsCache = Caffeine.newBuilder().maximumSize(1000).recordStats() // 开启统计.build(key -> loadData(key));// 使用一段时间后打印统计信息
System.out.println("缓存命中率:" + statsCache.stats().hitRate());
System.out.println("平均加载时间(纳秒):" + statsCache.stats().averageLoadNanos());
System.out.println("加载成功次数:" + statsCache.stats().loadSuccessCount());

Caffeine 就像一位精明的仓库管理员,既能快速找到你需要的物品(缓存命中),又能及时清理过期或不常用的物品(过期和淘汰策略),还会记录仓库的运作情况(统计功能)。它采用了先进的 "W-TinyLFU" 淘汰算法,能在有限的缓存空间里保留最可能被再次访问的数据,大大提高缓存命中率。

无论是 Web 应用中的热点数据缓存、数据库查询结果缓存,还是复杂计算结果的临时存储,Caffeine 都能以其出色的性能和灵活的配置,为你的应用加速。有了这个性能狂飙者,Java 应用的响应速度将得到显著提升,用户体验也会更上一层楼。