如何在不传递任何键的情况下从番石榴加载缓存中获取所有值

How to get all values from guava LoadingCache without passing any keys

我正在使用 Guava LoadingCache 缓存一些结果。使用加载方法,我从其他来源获取结果并使用“put(key,value)”放入缓存。 现在我要解决的问题是:我想在不传递任何密钥的情况下获取该缓存中的所有可用结果。因为我有兴趣获取当时缓存中显示的所有值,而不管任何特定的键。

那里有

getall(Iterable<?> keys)getAllPresent(Iterable<?> keys) 方法,但那些方法需要传递密钥。

您可以使用 (Loading)Cache#asMap view and operate on returned ConcurrentMap. There's nice description on Guava wiki page:

You can view any Cache as a ConcurrentMap using its asMap view, but how the asMap view interacts with the Cache requires some explanation.

  • cache.asMap() contains all entries that are currently loaded in the cache. So, for example, cache.asMap().keySet() contains all the currently loaded keys.