GuavaCache清除策略
GuavaCache的数据删除分为:被动删除和主动删除
删除通知
//CacheLoader的方式创建
LoadingCache<String,Object> cache= CacheBuilder.newBuilder()
/*
加附加的功能
*/
//最大个数 //统计命中率 //移除通知
.maximumSize(3).recordStats().removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> removalNotification) {
//移除的key 移除的原因
System.out.println(removalNotification.getKey()+":"+removalNotification.getCause());
}
})
.build(new CacheLoader<String, Object>() {
//读取数据源
@Override
public Object load(String key) throws Exception {
return Constants.hm.get(key);
}
});
//打印输出统计
System.out.println(cache.stats().toString());
public final class Constants {
/**
* 模拟数据源
*/
public static Map<String,String> map=new HashMap();
static {
map.put("1","张飞");
map.put("2","赵云");
map.put("3","马超");
map.put("4","关羽");
map.put("5","黄忠");
}
}
被动删除
基于数据大小的删除
LoadingCache<String,Object> cache= CacheBuilder.newBuilder()
/*
加附加的功能
*/
//最大个数
.maximumSize(3)
.build(new CacheLoader<String, Object>() {
//读取数据源
@Override
public Object load(String key) throws Exception {
return Constants.map.get(key);
}
});
//读取缓存中的1的数据 缓存有就读取 没有就返回null
System.out.println(cache.getIfPresent("5"));
基于过期时间的删除
隔多长时间后没有被访问过的key被删除
//缓存中的数据 如果3秒内没有访问则删除
.maximumSize(3).expireAfterAccess(3, TimeUnit.SECONDS)
。。。。
Thread.sleep(1000);
//访问1 1被访问
cache.getIfPresent("1");
//歇了2.1秒
Thread.sleep(2100);
写入多长时间后过期
//等同于expire ttl 缓存中对象的生命周期就是3秒
.maximumSize(3).expireAfterWrite(3, TimeUnit.SECONDS)
.build(new CacheLoader<String, Object>() {
//读取数据源
@Override
public Object load(String key) throws Exception {
return Constants.hm.get(key);
}
});
Thread.sleep(1000);
//访问1
cache.getIfPresent("1");
//歇了2.1秒
Thread.sleep(2100);
System.out.println("==================================");
//访问1
cache.getIfPresent("1");
基于引用的删除
可以通过weakKeys和weakValues方法指定Cache只保存对缓存记录key和value的弱引用。这样当没有 其他强引用指向key和value时,key和value对象就会被垃圾回收器回收。
LoadingCache<String,Object> cache = CacheBuilder.newBuilder()
// 最大3个 值的弱引用
.maximumSize(3).weakValues()
.build();
Object value = new Object();
cache.put("1",value);
value = new Object();//原对象不再有强引用
//强制垃圾回收
System.gc();
System.out.println(cache.getIfPresent("1"));
主动删除
单独删除
// 将key=1 删除
cache.invalidate("1");
批量删除
// 将key=1和2的删除
cache.invalidateAll(Arrays.asList("1","2"));
清空所有数据
// 清空缓存
cache.invalidateAll();