Spring集成GuavaCache实现本地缓存
Spring集成GuavaCache实现本地缓存:
一、SimpleCacheManager集成GuavaCache
1 package com.bwdz.sp.comm.util.test; 2 3 import com.google.common.cache.CacheBuilder; 4 import org.springframework.cache.CacheManager; 5 import org.springframework.cache.annotation.EnableCaching; 6 import org.springframework.cache.guava.GuavaCache; 7 import org.springframework.cache.support.SimpleCacheManager; 8 import org.springframework.context.annotation.Bean; 9 import org.springframework.context.annotation.Configuration; 10 11 import java.util.Arrays; 12 import java.util.concurrent.TimeUnit; 13 14 //@Configuration用于定义配置类,相当于把该类作为spring的xml配置文件,里面包含<beans>,作用为:初始化Spring容器(应用上下文) 15 //@EnableCaching注解驱动的缓存管理功能:不需要在XML文件中配置cache manager了,等价于<cache:annotation-driven/>.能够在服务类方法上标注@Cacheable 16 //@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的<bean>,作用为:注册bean对象 17 @Configuration 18 @EnableCaching 19 public class CacheConfig { 20 @Bean 21 public CacheManager localCacheManager() { 22 SimpleCacheManager simpleCacheManager = new SimpleCacheManager(); 23 //把各个cache注册到cacheManager中,GuavaCache实现了org.springframework.cache.Cache接口 24 simpleCacheManager.setCaches(Arrays.asList( 25 //CacheBuilder构建多个cache 26 new GuavaCache( 27 "TIMEOUT_1_HOURS",//定义cache名称:@Cacheable的cacheNames(等价value)属性要和此对应 28 CacheBuilder 29 .newBuilder() 30 .expireAfterWrite(1, TimeUnit.HOURS)//参数:过期时长、单位 31 .build() 32 ), 33 new GuavaCache( 34 "TIMEOUT_5_MINUTE", 35 CacheBuilder 36 .newBuilder() 37 .expireAfterWrite(5, TimeUnit.MINUTES) 38 .build() 39 ) 40 )); 41 return simpleCacheManager; 42 } 43 }
二、集成后直接加注解使用
1 //key:缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写(当然随便指定也不会报错) 2 @Cacheable(cacheNames = "TIMEOUT_1_HOURS", key = "'cache_getXfshxxss'") 3 public List<Map> getXfshxxss() throws Exception { 4 return (List<Map>) dao.findForList("XxkpsjtbMapper.getXfshxxss", null); 5 }
1、Spring中的cache是为方法做缓存的,spring只是提供了个缓存抽象,具体的实现由第三方提供(比如guava或者自己编写)
3、GuavaCache 支持多种缓存过期策略:定时过期、定时刷新等等
4、本地缓存:GuavaCache、ehcache、CaffeineCache,分布式缓存(网络缓存):redis、memcached
https://blog.csdn.net/qq_34531925/article/details/80864773
https://segmentfault.com/a/1190000011105644
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)