我有一个用@Cacheable 注释的方法。如果在方法内部捕获到异常,我希望清除缓存。但是,似乎缓存是在清除它的行之后执行的方面加载的。因此,当方法中捕获到异常时,即使清除了缓存,空字符串结果仍留在缓存中。
我应该从哪里清除缓存?
@Cacheable("myCache")
public String myMethod() {
String result="";
try {
result = doSomething();
} catch (Exception e) {
cacheManager.getCache("myCache").clear();
}
return token;
}
答案 0 :(得分:4)
好的 - 您可以使用注释上的一个属性。以下示例来自 (http://websystique.com/spring/spring-4-cacheable-cacheput-cacheevict-caching-cacheconfig-enablecaching-tutorial/)
<块引用>除非:条件缓存,适用于方法的返回值。物品 将被缓存,除非满足“除非”中提到的条件。笔记 该条件适用于方法的返回值。#result 指的是 方法返回值。
@Cacheable(value="products", key="#product.name", condition="#product.price<500", unless="#result.outofstock")
public Product findProduct(Product product){
..
return aproduct;
}
因此,您可以使用 unless="#result.length() == 0"
并在错误情况下或在您不希望缓存结果的任何其他时间返回一个空字符串。