2017-04-25 49 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',因此不適用於堆外的任何緩存。 –