干掉 Caffeine ,Cache2K才是本地缓存的王
聊起来 Java 内存缓存库,大家随口而出的就是老牌大哥 Ehcache、新晋王者 Caffeine,在最新 SpringBoot 2.7 中添加了 Cache2k[1] 的依赖项管理和自动配置,意味着 Cache2k 正式得到 Spring 官方的认可
引起了我对这个开源的轻量级、高性能 Java 内存缓存库的重视。
benchmarks 测试[2] 如下,在吞吐量方面相较于 Ehcache3、Caffeine 有了大幅度提升
一、如何使用
本文以最新的 spring boot 2.7 为例
① 引入依赖
<dependency>
<groupId>org.cache2kgroupId>
<artifactId>cache2k-springartifactId>
dependency>
② 配置 Cache 类型
③ spring cache 注解体验
@Cacheable(value = "demo", key = "#key")
public String get(String key) {
return "success";
}
二、进阶配置
个性化参数
通过实现 Cache2kBuilderCustomizer 接口实现缓存个性化
public class CustomCache2kBuilderCustomizer implements Cache2kBuilderCustomizer {
/**
* Customize the default cache settings.
*
* @param builder the builder to customize
*/
@Override
public void customize(Cache2kBuilder, ?> builder) {
// 个性化
}
}
micrometer 指标监控
org.cache2k
cache2k-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-02 03:41:34.367, cleared=-, infoCreated=2016-12-02 14: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 项目
参考资料
Cache2k: https://cache2k.org
[2]benchmarks 测试: https://cache2k.org/benchmarks.html
加入群聊
评论