Caffeine getIfPresent()返回 null 问题
作者:@caseyfu
本文为作者原创,转载请注明出处:https://www.cnblogs.com/caseor/p/caffeine-returns-null.html
目录
问题
参考
Caffeine getIfPresent()返回 null 问题
问题
集成 Caffeine 时, 将 Cache 注册为全局的 Bean, 然后通过@Autowired 自动装配
使用 cache.put(key, val) 和 cache.getIfPresent(key) 放入和获取缓存
@Configuration public class CaffeineConfig { @Bean public Cache<String, Object> cache() { return Caffeine.newBuilder() // 数量 .maximumSize(1024) .expireAfterWrite(30, TimeUnit.MINUTES) // 弱引用 .weakKeys() .weakValues() // 删除监听事件 .removalListener( (RemovalListener<String, Object>) (key, val, reason) -> System.out.println("key:" + key + ", val:" + val + ", reason:" + reason) ).build(); } }
@RestController public class CaffeineController { private final Cache<String, Object> cache; @Autowired public CaffeineController(Cache<String, Object> cache) { this.cache = cache; } @PostMapping("/add") public Result add(String key, String val) { cache.put(key, val); return Result.success("add success"); } @GetMapping public Result get(String key) { return Result.success((String) cache.getIfPresent(key)); } }
无论如何调用, get()总是返回 null, 最后找到问题所在, 是配置的 Bean 有问题。
在构造 Bean 时添加了参数.weakKeys()[1], 使 key 成为弱引用变量, 被垃圾回收器发现之后就会被回收掉
key被回收掉之后获取缓存时要使用==
(比较地址)而不是equals()
(比较值)来获取缓存[2]。
去掉.weakKeys()之后, 可以成功取得缓存!
参考
[1] getIfPresent caffeine return null, https://stackoverflow.com/questions/63068085/getifpresent-caffeine-return-null
[2] Caffeine 缓存, xiaolyuh, https://www.jianshu.com/p/9a80c662dac4
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
2020-06-26 windows使用.bat文件批量执行任务