Caffeine 或任何 JVM 缓存的逐出事件侦听器 API?

Eviction Event Listeners for Caffeine or any JVM Cache API?

Java 8 在这里。 Caffeine 缓存框架(或与此相关的任何其他 JSR-107 兼容框架)是否有任何方法可以在记录被逐出缓存时得到通知?

也许是某种 EvictionEventListener 之类的?

public class MyEvictionListener implements EvictionEventListener<String> {
    @Override
    public void onEvictionEvent(EvictionEvent eviction, String key) {
        // Now I have access to the String "key" that was evicted and
        // some information surrounding the eviction and I can do
        // whatever I want with this information....
    }
}

Caffeine、Guava、Hazelcast、(基本上是“JVM cache land”)等有类似的东西吗?

按时间或 space 逐出 ?

在 JSR107 中,您必须为前者获取事件,而不能为后者获取事件。 请参阅规范“8.4. 监听器调用”的第 8.4 节。

所有 JCache 实现都必须支持按时间逐出,您会通过 javax.cache.event.CacheEntryExpiredListener<K, V> 了解这一点。根据实施情况,过期可以是急切的或惰性的,项目不一定会在其时间限制发生时消失。

JCache 允许实现基于 space 扩展它。

使用 Hazelcast,您可以做到这一点

 <eviction size="50" max-size-policy="ENTRY_COUNT" eviction-policy="LRU"/>

根据可配置的 space 阈值丢弃缓存中的项目。但是,由于这取决于实现,因此没有 JCache 事件。

JCache的EXPIRED事件是系统产生的,用户不能直接触发。 REMOVED 事件仅适用于用户发起的操作,例如 cache.remove(k)。其他两种 CREATEDUPDATED 在这里也无济于事。