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}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术