springboot 使用caffeine 并监控本地缓存

发布时间 2023-07-14 18:03:40作者: 蜗牛无敌

1、添加依赖

   <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>

 

2、添加配置

package com.example.demo.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
@EnableScheduling
public class PageCacheConfig {

    public Cache<String, String> cache;


    @PostConstruct
    private Cache<String, String> caffeineCacheBuilder() {
        cache = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.SECONDS)
                .maximumSize(100).recordStats().build();
        return cache;
    }

    @Scheduled(fixedRate = 1000) // 每秒执行一次
    public void printCacheHitRate() {
        /**
         * hitCount–缓存命中数
         *
         * missCount–缓存未命中数
         *
         * loadSuccessCount–成功加载缓存的次数
         *
         * loadFailureCount–缓存加载失败的次数
         *
         * totalLoadTime–总加载时间(成功和失败)
         *
         * evictionCount–从缓存中逐出的条目数
         *
         * ejectionWeight–从缓存中逐出的条目的权重之和
         */
        CacheStats stats = cache.stats();
        System.out.println("Cache hit rate: " + stats);
    }

}

 

 

 

 

3、测试controller

package com.example.demo.controller;

import com.example.demo.config.PageCacheConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LocalCacheTestController {
    @Autowired
    PageCacheConfig pageCacheConfig;

    @GetMapping("/saveCache")
    public String addCache(@RequestParam("key") String key, @RequestParam("value") String value) {
        pageCacheConfig.cache.put(key, value);
        return "ok";
    }

    @GetMapping("/getCache")
    public String addCache(@RequestParam("key") String key) {
        String value = pageCacheConfig.cache.getIfPresent(key);
        return value;
    }
}

 

4、测试

1、保存缓存
http://127.0.0.1:8080/saveCache?key=name&value=zhangshan
2、获取缓存
http://127.0.0.1:8080/getCache?key=name

5、监控

CacheStats{hitCount=1, missCount=0, loadSuccessCount=0, loadFailureCount=0, totalLoadTime=0, evictionCount=0, evictionWeight=0}