guava

缓存分为:本地缓存 分布式缓存
本地缓存:
https://blog.csdn.net/weixin_42578444/article/details/80878611
guava和ehcache都是本地缓存,在guava之前用的是ConcurrentMap,因为能友好的支持并发。但它并不支持缓存的一些特性,比如缓存过期、缓存数据加载和刷新
使用场景:1、愿意消耗一些本地内存空间提升速度 2、更新锁定当某个缓存失效的时候,大量请求去查询某一个key 当这个key不存在,就会导致多次从数据库中加载数据,Guava cache 可以在cacheloader 的 load方 法众加以控制,对同一个key只让一个请求去数据库众读取数据,而其他请求阻塞等待结果。

Guava Cache
1.使用key, value 的形式存储数据 LoadingCache<String, TestCase> testCaseExecLoadingCache
2.定义缓存对象,重写接口:load接口,当get的不存在的时候,调用load方法
testCaseExecLoadingCache = CacheBuilder.newBuilder()
.refreshAfterWrite(3, TimeUnit.HOURS)// 给定时间内没有被读/写访问,则回收。
.expireAfterAccess(16, TimeUnit.HOURS)// 缓存过期时间和redis缓存时长一样
.maximumSize(800)// 设置缓存个数
.build(new CacheLoader<String, TestCase>() {
@Override
/** 当本地缓存命没有中时,调用load方法获取结果并将结果缓存 **/
public TestCase load(String testCaseCacheKey) throws SQLiteAccessException {
/** 拆分testCaseCacheKey,格式:fileMD5{}testCaseFullPath*/
String testCaseFullPath = Common.substringAfter(testCaseCacheKey, "{}");
System.out.println("load 无缓存" + testCaseFullPath);
return findTestCaseFile(testCaseFullPath);
}
/**
* jarKey组装逻辑为 jarId{}jarFileName,获取class list
* @param tesCaseKey 全路径
* @return
*/
private TestCase findTestCaseFile(String tesCaseFullPath) {
TestCase oTestCase = null;
try {
TestCaseFile oCaseFile = new TestCaseFile(tesCaseFullPath);
oTestCase = oCaseFile.readCaseRoot();
}catch(Exception e) {

}
return oTestCase;
}
});
3.提供 put/get/invalidate方法等

原文地址:https://www.cnblogs.com/wangyingshuo/p/14116893.html