当前位置: 首页 > news >正文

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。
  • 适用场景:
    • 数据频繁读取但不经常变化的场景。
    • 需要快速响应的本地缓存需求。

相关文章:

  • 归一化对C4.5决策树无效的数学原理与实证分析
  • ios17 音频加载失败问题
  • 基础服务系列-Mac Ngrok 内网穿透
  • 如何在腾讯云Ubuntu服务器上部署Node.js项目
  • Novartis诺华制药社招入职综合能力测评真题SHL题库考什么?
  • 在kali中安装AntSword(蚁剑)
  • 【 Git 全局忽略文件完全指南:配置、规则与最佳实践】
  • 强化学习系统学习路径与实践方法
  • 微软Edge浏览器字体设置
  • 在线查看【免费】avi,mov,rm,webm,ts,rm,mkv,mpeg,ogg,mpg,rmvb,wmv,3gp,ts,swf文件格式网站
  • 部署Kimi-VL-A3B-Instruct视频推理
  • GPU软硬件架构协同设计解析
  • EtherCAT 模型(Reference Model)
  • 使用 inobounce 解决 iOS 皮筋效果导致的无法下拉刷新
  • 【形式化验证基础】活跃属性Liveness Property和安全性质(Safety Property)介绍
  • 利用Qt创建一个模拟问答系统
  • HCIE Datacom备考技巧
  • Kubernetes相关的名词解释POD(13)
  • Argo CD
  • 递归神经网络
  • 蔚来第三品牌萤火虫上市:对标宝马MINI,预期贡献10%销量
  • 市场监管部门完成全国保健食品生产企业体系检查首轮全覆盖
  • 分离19年后:陈杨梅首度露面,父亲亲手喂棉花糖给女儿吃
  • 文化中国行|1500年水镇枫泾有座丁聪美术馆
  • 从6家试点扩展至全行业,券商并表监管有何看点?
  • 撤销逾千名留学生签证,特朗普政府面临集体诉讼