番石榴缓存:放置操作触发删除侦听器



>我有一个缓存,正在将新元素放入其中。每次我将项目放入缓存中时,都会触发删除侦听器。如何让删除侦听器仅在实际删除或逐出内容时触发?

Cache<String, String> cache = CacheBuilder.newBuilder()
//      .expireAfterWrite(5, TimeUnit.MINUTES)
.removalListener((RemovalListener<String, String>) notification -> {
System.out.println("Why");
})
.build();
}
cache.put("a","b"); // triggers removal listener

我在这里错过了什么吗?为什么不叫PutListener

要找到实际原因,应使用 RemovalNotification.getCause(( 方法。

要处理除"替换条目"事件通知之外的所有事件通知,请考虑以下实施草案:

class RemovalListenerImpl implements RemovalListener<String, String> {
@Override
public void onRemoval(final RemovalNotification<String, String> notification) {
if (RemovalCause.REPLACED.equals(notification.getCause())) {
// Ignore the «Entry replaced» event notification.
return;
}
// TODO: Handle the event notification here.
}
}

最新更新