guava cache 例子
所属分类 guava
浏览量 1410
LoadingCache
CacheBuilder.newBuilder()
常用参数
1. 缓存数据最大个数 CacheBuilder.maximumSize(long)
2. 过期时间 expireAfterAccess(long, TimeUnit) expireAfterWrite(long, TimeUnit)
3. 引用类型 CacheBuilder.weakKeys() CacheBuilder.weakValues() CacheBuilder.softValues()
4. 自动刷新 CacheBuilder.refreshAfterWrite
5. 过期时间 CacheBuilder.expireAfterWrite
load方法 不能返回 null ,
com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key 3
调用 recordStats() 才会 记录统计数据 ,否则都是0
Without this will return zero for all statistics
CacheStats{hitCount=14, missCount=21, loadSuccessCount=18, loadExceptionCount=3, totalLoadTime=43051592, evictionCount=6}
hitCount=14,
missCount=21
loadSuccessCount=18
loadExceptionCount=3
totalLoadTime=43051592
evictionCount=6
LoadingCache cache = CacheBuilder.newBuilder()
// Without this will return zero for all statistics
.recordStats()
.maximumSize(7)
// .refreshAfterWrite(3, TimeUnit.SECONDS)
//软引用
// .softValues()
.expireAfterWrite(3, TimeUnit.SECONDS)
// .expireAfterAccess(duration, unit)
.build(new CacheLoader() {
@Override
public String load(Integer key) throws Exception {
if(key>=3){
// com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key 3
//return null;
return "NULL";
}
SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
return key+"_"+sdf.format(new Date());
}
});
完整代码
https://gitee.com/dyyx/demos/blob/master/guava/src/main/java/dyyx/CacheTest.java
上一篇
下一篇
管理学定律
程序员的爱情
guava RateLimiter 限流例子
2019容器使用情况
银行业务简介
prometheus特殊指标