Null 如何使用Ehcache 3缓存空值
我需要用Ehcache 3缓存空值。 对于Ehcache2,我发现如下示例:Null 如何使用Ehcache 3缓存空值,null,ehcache,ehcache-3,Null,Ehcache,Ehcache 3,我需要用Ehcache 3缓存空值。 对于Ehcache2,我发现如下示例: //缓存显式空值: put(新元素(“key”,null)); Element=cache.get(“key”); if(元素==null){ //缓存中没有“密钥”的内容(或已过期)。。。 }否则{ //缓存中存在有效元素,但getObjectValue()可能为空: Object value=element.getObjectValue(); 如果(值==null){ //缓存中存在空值。。。 }否则{ //
//缓存显式空值:
put(新元素(“key”,null));
Element=cache.get(“key”);
if(元素==null){
//缓存中没有“密钥”的内容(或已过期)。。。
}否则{
//缓存中存在有效元素,但getObjectValue()可能为空:
Object value=element.getObjectValue();
如果(值==null){
//缓存中存在空值。。。
}否则{
//缓存中存在非空值。。。
当然,如果我的返回对象为null,我可以构建一些逻辑。如果我只存储null元素的密钥,我可以将其放入另一个集合。当然,为了阅读,我需要检查我的ehcache和我的“特殊”集合。您的问题包含答案,您需要使用或相关的解决方案包装/隐藏您的
null
s
Ehcache 3中不支持也不会支持
null
键或值。我只是创建了一个null占位符类
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()));
Serializable value = EHCache3Null.checkForNullOnGet((Serializable) cache.get(key));
然后在我的get操作中:
cache.put(element.getKey(), EHCache3Null.checkForNullOnPut(element.getValue()));
Serializable value = EHCache3Null.checkForNullOnGet((Serializable) cache.get(key));
到目前为止非常感谢。我还以为Ehcache2也会有一些配方。我想我会使用这里描述的东西:在null的情况下使用`Boolean.FALSE或其他任何东西。请注意,
可选
不可序列化
,因此不适用于堆之外的任何缓存。