Guava Cache 缓存数据被移除后的监听器RemovalListener

Guava Cache的RemovalListener允许在数据被移除时接收通知,便于进行额外处理。当使用invalidate()清除缓存时,注册的监听器会被触发,RemovalNotification携带key、value和移除原因。默认情况下,监听器同步执行可能导致调用者线程阻塞。为避免这种情况,可以使用异步监听器RemovalListeners.asynchronous()来提高效率。
摘要由CSDN通过智能技术生成

之前文章已经介绍了guava的容量管理,有4种方式可以将数据从缓存中移除。有的时候,我们需要在缓存被移除的时候,得到这个通知,并做一些额外处理工作。这个时候RemovalListener就派上用场了。

public class Main {

	// 创建一个监听器
	private static class MyRemovalListener implements RemovalListener<Integer, Integer> {
	@Override
	public void onRemoval(RemovalNotification<Integer, Integer> notification) {
		String tips = String.format("key=%s,value=%s,reason=%s", notification.getKey(), notification.getValue(), notification.getCause());
		System.out.println(tips);
	}
	}

	public static void main(String[] args) {

	// 创建一个带有RemovalListener监听的缓存
	Cache<Integer, Integer> cache = CacheBuilder.newBuilder().removalListener(new MyRemovalListener()).build();

	cache.put(1, 1);

	// 手动清除
	cache.invalidate(1);

	System.out.println(cache.getIfPresent(1)); // null
	}

}


使用invalidate()清除缓存数据之后,注册的回调被触发了。



RemovalNotification中包含了缓存的key、value以及被移除的原因RemovalCause。通过源码可以看出,移除原因与容量管理方式是相对应的。

public enum RemovalCause {
  /**
   * The entry was manually removed by the user. This can result from the user invoking
   * {@link Cache#invalidate}, {@link Cache#invalidateAll(Iterable)}, {@link Cache#invalidateAll()},
   * {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link Iterator#remove}.
   */
  EXPLICIT {
    @Override
    boolean wasEvicted() {
      return false;
    }
  },

  /**
   * The entry itself was not actually removed, but its v
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值