guava cache 的监控

梦康 2022-12-07 22:18:10 79

新项目推荐大家使用 Caffeine,监控配合 springboot2 的spring-boot-starter-actuator 监控,我这里使用的比较简单的定时任务去监控

Collection<String> caches = cacheManager.getCacheNames();

caches.forEach(cacheName -> {
    log.info(cacheName);
    Cache cache = cacheManager.getCache(cacheName);
    com.google.common.cache.Cache nativeCache = (com.google.common.cache.Cache) cache.getNativeCache();
    CacheStats cacheStats = nativeCache.stats();
    log.info("size:{},memory:{}M,hitRate:{}%,hitCount:{},loadCount:{},evictionCount:{}",
            nativeCache.size(),
            String.format("%.2f", (double) ObjectSizeCalculator.getObjectSize(nativeCache) / (1024 * 1024)),
            String.format("%.2f", cacheStats.hitRate() * 100),
            cacheStats.hitCount(),
            cacheStats.loadCount(),
            cacheStats.evictionCount());
});

最后输出结果类似于

size:160,memory:1.95M,hitRate:43.86%,hitCount:125,loadCount:160,evictionCount:0
size:477,memory:6.36M,hitRate:50.11%,hitCount:6567,loadCount:6531,evictionCount:6054
size:364,memory:4.08M,hitRate:52.02%,hitCount:10585,loadCount:9751,evictionCount:9387