显式清除
任何时候,你都可以显式地清除缓存项,而不是等到它被回收:
个别清除:Cache.invalidate(key)
批量清除:Cache.invalidateAll(keys)
清除所有缓存项:Cache.invalidateAll()
移除监听器
通过CacheBuilder.removalListener(RemovalListener),你可以声明一个监听器,以便缓存项被移除时做一些额外操作。缓存项被移除时,
RemovalListener会获取移除通知[RemovalNotification],其中包含移除原因[RemovalCause]、键和值。
任何时候,你都可以显式地清除缓存项,而不是等到它被回收:
个别清除:Cache.invalidate(key)
批量清除:Cache.invalidateAll(keys)
清除所有缓存项:Cache.invalidateAll()
移除监听器
通过CacheBuilder.removalListener(RemovalListener),你可以声明一个监听器,以便缓存项被移除时做一些额外操作。缓存项被移除时,
RemovalListener会获取移除通知[RemovalNotification],其中包含移除原因[RemovalCause]、键和值。
例如:(使用方式)
public <K, V> LoadingCache<K, V> cached(CacheLoader<K, V> cacheLoader) {
LoadingCache<K, V> cache = CacheBuilder.newBuilder().maximumSize(2).weakKeys().softValues().refreshAfterWrite(120, TimeUnit.SECONDS).expireAfterWrite(10, TimeUnit.MINUTES).removalListener(new RemovalListener<K, V>() {
@Override
public void onRemoval(RemovalNotification<K, V> rn) {
System.out.println(rn.getKey() + "被移除");
}
}).build(cacheLoader);
return cache;
}
/**
* 通过key获取value 调用方式 commonCache.get(key) ; return String
*
* @param key
* @return
* @throws Exception
*/
public LoadingCache<String, String> commonCache(final String key) throws Exception {
LoadingCache<String, String> commonCache = cached(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
return "hello " + key + "!";
}
});
return commonCache;
}
@Test
public void testCache() throws Exception {
LoadingCache<String, String> commonCache = commonCache("1");
System.out.println("1:" + commonCache.get("1"));
// commonCache.apply("harry");
System.out.println("2:" + commonCache.get("2"));
// commonCache.apply("lisa");
System.out.println("3:" + commonCache.get("3"));
commonCache.invalidateAll();
}