如何使用 Ehcache 3 缓存空值

tim*_*guy 2 null ehcache ehcache-3

我需要使用 Ehcache 3 缓存空值。对于 Ehcache 2,我找到了如下示例:

// cache an explicit null value:
cache.put(new Element("key", null));

Element element = cache.get("key");

if (element == null) {

// nothing in the cache for "key" (or expired) ...
} else {

// there is a valid element in the cache, however getObjectValue() may be null:

Object value = element.getObjectValue();

if (value == null) {

    // a null value is in the cache ...

} else {

    // a non-null value is in the cache ...
Run Code Online (Sandbox Code Playgroud)

Ehcache 3 是否有这样的示例,因为 net.sf.ehcache.Element 似乎不再存在?

我也看到了这个评论:https ://github.com/ehcache/ehcache3/issues/1607

事实上,你不能缓存空值,这也是 JCache 规范的行为。如果您的应用程序中需要此值,请创建一个哨兵值或包装应用程序中的值。

当然,如果我的返回对象为 null,我可以构建一些逻辑,将其放入另一个 Set 中,而我只存储 null 元素的键。当然,为了阅读,我需要检查我的 ehcache 和我的“特殊”集。

Lou*_*met 5

您的问题包含答案,您需要使用空对象模式或相关解决方案来包装/隐藏您的nulls.

nullEhcache 3 中不存在也不会支持键或值。