一、springboot缓存
springboot支持很多种缓存方式:redis、guava、ehcahe、jcache等等。
二、guava介绍
guava cache 是 google 开源的一套开发工具集合,guava cache 是其中的一个专门用于处理本地缓存的轻量级框架,是全内存方式的本地缓存,而且是线程安全的。
和 concurrentmap 相比,guava cache 可以限制内存的占用,并可设置缓存的过期时间,可以自动回收数据,而 concurrentmap 只能通过静态方式来控制缓存,移除数据元素需要显示的方式来移除。
三、 缓存回收方式
1、基于容量回收
2、基于时间回收
3、基于引用回收
cachebuilder.weakvalues():和 cachebuilder.weakkeys() 方法类似,该方法按照弱引用方式来存储缓存项的值,允许系统垃圾回收时回收缓存项。
cachebuilder.weakvalues(),使用软引用方式来包装缓存值,只有在内存需要时(一般在接近内存溢出时),系统会按照全局lru(least-recently-used)原则进行垃圾回收。考虑到垃圾回收的性能问题,推荐使用基于容量的回收方式。
4、手动回收
guava使用
导入依赖
<dependency> <groupid>com.google.guava</groupid> <artifactid>guava</artifactid> <version>20.0</version> </dependency>
recordstats:开启统计功能
stats:查看统计情况
void testrecordstats(){ cache<string, string> callcache = cachebuilder.newbuilder(). initialcapacity(5) .maximumsize(100) .recordstats() .expireafteraccess(1, timeunit.seconds) .build(); /** * cachestats{hitcount=0, misscount=0, loadsuccesscount=0, loadexceptioncount=0, totalloadtime=0, evictioncount=0} */ cachestats stats = callcache.stats(); system.out.println(stats); }
并发级别
调整concurrencylevel即可
5、代码实例
/** * @author sprem至尊 * @date 2022/10/24 19:39 * @version 1.0 */ package com.cn.xiaonuo.modular.wechat.cache; import com.google.common.cache.cachebuilder; import com.google.common.cache.cacheloader; import com.google.common.cache.loadingcache; import org.springframework.stereotype.component; import java.util.concurrent.timeunit; @component public class tokencache { private static loadingcache<string,string> loadingcache = cachebuilder .newbuilder().initialcapacity(100).maximumsize(100) .expireafterwrite(7000, timeunit.seconds) .build(new cacheloader<string, string>() { @override public string load(string key) throws exception { return null; } }); public static void setkey(string key,string value){ loadingcache.put(key, value); } public static string getvalue(string key){ string value = null; try{ value = loadingcache.get(key); if(value == null){ return null; } return value; }catch (exception e){ return null; } } }
到此这篇关于springboot整合guava实现本地缓存的示例代码的文章就介绍到这了,更多相关springboot guava本地缓存内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论