您的位置:首页 >聚焦 >

干掉 Caffeine ,Cache2K才是本地缓存的王

2022-06-10 08:39:26    来源:程序员客栈

聊起来 Java 内存缓存库,大家随口而出的就是老牌大哥 Ehcache、新晋王者 Caffeine,在最新 SpringBoot 2.7 中添加了 Cache2k[1]的依赖项管理和自动配置,意味着 Cache2k 正式得到 Spring 官方的认可

引起了我对这个开源的轻量级、高性能 Java 内存缓存库的重视。

benchmarks 测试[2]如下,在吞吐量方面相较于 Ehcache3、Caffeine 有了大幅度提升
吞吐性能测试
一、如何使用

本文以最新的 spring boot 2.7 为例

① 引入依赖

org.cache2kcache2k-spring

② 配置 Cache 类型
指定Cache类型
③ spring cache 注解体验

@Cacheable(value="demo",key="#key")publicStringget(Stringkey){return"success";}

二、进阶配置个性化参数
SpringCache2kCacheManager
通过实现 Cache2kBuilderCustomizer 接口实现缓存个性化

publicclassCustomCache2kBuilderCustomizerimplementsCache2kBuilderCustomizer{/***Customizethedefaultcachesettings.**@parambuilderthebuildertocustomize*/@Overridepublicvoidcustomize(Cache2kBuilderbuilder){//个性化}}

micrometer 指标监控

org.cache2kcache2k-micrometer

输出缓存的一些关键信息和状态,可整合 Prometheus

Cache{database}(size=50003,capacity=50000,get=102876307,miss=1513517,put=0,load=4388352,reload=0,heapHit=101362790,refresh=2874835,refreshFailed=42166,refreshedHit=2102885,loadException=0,suppressedException=0,new=1513517,expire=587294,remove=8156,clear=0,removeByClear=0,evict=868064,timer=3462129,goneSpin=0,hitRate=98.52%,msecs/load=0.425,asyncLoadsStarted=2874835,asyncLoadsInFlight=0,loaderThreadsLimit=8,loaderThreadsMaxActive=8,created=2016-12-0203:41:34.367,cleared=-,infoCreated=2016-12-0214:34:34.503,infoCreationDeltaMs=21,collisions=8288,collisionSlots=7355,longestSlot=5,hashQuality=83,noCollisionPercent=83,impl=HeapCache,eviction0(impl=ClockProPlusEviction,chunkSize=11,coldSize=749,hotSize=24252,hotMaxSize=24250,ghostSize=12501,coldHits=11357227,hotHits=38721511,ghostHits=294065,coldRunCnt=444807,coldScanCnt=698524,hotRunCnt=370773,hotScanCnt=2820434),eviction1(impl=ClockProPlusEviction,chunkSize=11,coldSize=778,hotSize=24224,hotMaxSize=24250,ghostSize=12501,coldHits=11775594,hotHits=39508458,ghostHits=283324,coldRunCnt=423258,coldScanCnt=674762,hotRunCnt=357457,hotScanCnt=2689129),evictionRunning=0,keyMutation=0)

总结cache2k 的 jar 400kb 且无任何其他依赖,同样试用于 Android 项目2. 不流行的原因: 性能方面虽然不输于 Caffeine ,但国内相关的介绍较少参考资料[1]

Cache2k: https://cache2k.org

[2]

benchmarks 测试: https://cache2k.org/benchmarks.html

加入群聊

关键词: 参考资料 大幅度提升 性能测试

相关阅读