Caches
A LoadingCache is a Cache built with an attached CacheLoader. Creating a CacheLoader is typically as easy as implementing the method V load(K key) throws Exception.
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(MY_LISTENER)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
主要的类
- CacheLoader: 负责加载缓存
- CacheBuilder: 生成Cache实例的创建者,配置各项Cache属性
- RemovalListener: Cache数据移除事件的监听器
- CacheStats: Cache的统计功能
Eviction 数据回收的方式
- 缓存容量策略
CacheBuilder.maximumSize(long): 基于缓存元素的数量
- 缓存元素权重
CacheBuilder.weigher(Weigher)CacheBuilder.maximumWeight(long): 基于缓存元素的权重限制
- 根据时间策略
expireAfterAccess(long, TimeUnit): 最后一次访问操作后,超时失效expireAfterWrite(long, TimeUnit): 最后一次写操作后,超时失效
- 指定引用级别,默认key,value都是强引用
CacheBuilder.weakKeys()CacheBuilder.weakValues()CacheBuilder.softValues()
Explicit Removals
- individually, using
Cache.invalidate(key) - in bulk, using
Cache.invalidateAll(keys) - to all entries, using
Cache.invalidateAll()
Refresh 缓存数据的刷新
LoadingCache.refresh(K)CacheLoader.reload(K, V)CacheBuilder.refreshAfterWrite(long, TimeUnit)
// Some keys don't need refreshing, and we want refreshes to be done asynchronously.
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) { // no checked exception
return getGraphFromDatabase(key);
}
public ListenableFuture<Graph> reload(final Key key, Graph prevGraph) {
if (neverNeedsRefresh(key)) {
return Futures.immediateFuture(prevGraph);
} else {
// asynchronous!
ListenableFutureTask<Graph> task = ListenableFutureTask.create(new Callable<Graph>() {
public Graph call() {
return getGraphFromDatabase(key);
}
});
executor.execute(task);
return task;
}
}
});
Statistics 统计功能
By using CacheBuilder.recordStats(), you can turn on statistics collection for Guava caches. The Cache.stats() method returns a CacheStats object, which provides statistics such as
hitRate(), which returns the ratio of hits to requestsaverageLoadPenalty(), the average time spent loading new values, in nanosecondsevictionCount(), the number of cache evictions