我需要使用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 ...
Ehcache 3是否有这样的示例,因为看起来net.sf.ehcache.Element不再存在了?
我也看过这条评论:https://github.com/ehcache/ehcache3/issues/1607
实际上,您无法缓存空值,这也是JCache规范的行为。 如果您在应用程序中需要它,请创建一个sentinel值或从您的应用程序中包装您的值。
当然,如果我的返回对象是null,我可以构建一些逻辑将它放到另一个Set中我只存储我的空元素键。当然也是为了阅读我需要检查我的ehcache和我的“特殊”Set。
答案 0 :(得分:3)
您的问题包含答案,您需要使用null object pattern或相关解决方案来包装/隐藏null
。
在Ehcache 3中没有,也不会支持null
个键或值。
答案 1 :(得分:0)
我只是创建了一个空的占位符类。
public class EHCache3Null implements Serializable {
private static final long serialVersionUID = -1542174764477971324L;
private static EHCache3Null INSTANCE = new EHCache3Null();
public static Serializable checkForNullOnPut(Serializable object) {
if (object == null) {
return INSTANCE;
} else {
return object;
}
}
public static Serializable checkForNullOnGet(Serializable object) {
if (object != null && object instanceof EHCache3Null) {
return null;
} else {
return object;
}
}
}
然后当我使用缓存时,我在put操作中有以下内容:
cache.put(element.getKey(), EHCache3Null.checkForNullOnPut(element.getValue()));
然后我的get操作:
Serializable value = EHCache3Null.checkForNullOnGet((Serializable) cache.get(key));