Google Guava 缓存每次调用加载方法,即使键存在

Google Guava cache calling load method every time even if the key exists

我正在尝试像使用 Guice 一样使用 Guava Cache [版本 29.0-jre],如下所示:

我的观察是,Guava 缓存每次都会调用 load 方法,即使缓存中存在键也是如此。为什么会这样?

在上面的调试控制台中,我们可以观察到键 [uuid] 和值 [json object] 已经存在于缓存中。但是,在下一个 get 请求中,控件仍然进入 load 方法。

另一个观察结果是,我尝试了多次尝试,可以看到缓存中多次加载了具有相同密钥的条目。

we can observe that the key [uuid]

这是你的错误。那不是关键。您自己说过:.weakKeys() 在您的 CacheBuilder 设置中。关键不是 UUID,而是代表它的对象的标识。

来自 CacheBuilder 文档:

Note: by default, the returned cache uses equality comparisons (the equals method) to determine equality for keys or values. However, if weakKeys() was specified, the cache uses identity (==) comparisons instead for keys. Likewise, if weakValues() or softValues() was specified, the cache uses identity comparisons for values.

因此,密钥不是您看到的 UUID。它是该 UUID 对象的文字对象标识。让我试着用一个例子来解释。想象一下你的缓存有字符串键。

// Without .weakKey:

String a = new String("Hello");
String b = new String("Hello");

are the same key.

// With .weakKey THEY ARE NOT, because..

a == b; // this is false. Thus, .weakKeys() cache says not equal.
a.equals(b); // this is true. Thus, strong keys cache says equal.

您似乎既想要 'use .equals for identity' 方面,又想要“...但不要妨碍垃圾回收”方面。我不知道有什么简单的方法可以做到这一点。