0

@Cacheable我通过在具有以下声明的方法上使用注释来启用缓存:

@Cacheable(value = "myCache", key = "#t+ '_' + #key", condition = "#key != null")
public <T> T get(String t, VendorProperty<T> key, T defaultValue) {
    return get(t, key).orElse(default_value);
}

但是,NotSerializableException如果它尝试缓存的对象不是可序列化的(例如:),则会抛出此错误DateTimeFormatter

我想知道是否可以仅在对象可序列化时才缓存对象以避免此异常。

我正在使用库memcache来缓存对象simple-spring-memcache

PS:我无法将Serializable接口作为DateTimeFormatter预定义的类来实现。

4

2 回答 2

4

您可以指定条件:

 condition = "#key != null && #root.target instanceof T(java.io.Serializable)"
于 2018-12-07T07:28:22.093 回答
0

上面的建议是行不通的。#root.target 是正在执行的目标对象(在本例中为服务对象)。所以它似乎可以工作,因为服务对象是不可序列化的,所以有问题的对象不会被缓存,但其他任何东西也不会。

您需要使用结果变量来利用“除非”条件:

@Cacheable(value = "myCache", 
           key = "#t+ '_' + #key", 
           condition = "#key != null"
           unless="!(#result instanceof T(java.io.Serializable))")
于 2019-06-16T02:42:59.970 回答