2017-04-25 107 views
0

我需要的Ehcache 3. 缓存空值的Ehcache 2,我发现喜欢这里的例子:如何缓存空值与3的Ehcache

// 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 ... 

Ar e ehcache 3的例子,因为它似乎net.sf.ehcache.Element不存在了吗?

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

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

当然,我可以建立一些逻辑,如果我的返回对象为空把它放到另一个集我是只存储我的关键为null元素。当然,对于阅读我需要检查我的ehcache和我的“特殊”集。

回答

3

您的问题包含答案,您需要使用null object pattern或相关解决方案来包装/隐藏您的null s。

没有,并且也不会有,在3的Ehcache

+0

感谢null键或值为止的支持。只是认为Ehcache2也可能有某种配方。我想我会像这里描述的东西:http://stackoverflow.com/questions/4473579/ehcache-using-selfpopulatingcache-when-data-is-not-present使用Boolean.FALSE或任何情况下为空。 – timguy

+1

@timguy,Java 8的java.util.Optional是一个很好的包装器。 –

+1

请注意,'Optional'不是'Serializable',因此不适用于堆外的任何缓存。 –