java—从带有@cacheable注解的方法中清除缓存

i7uq4tfw  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(1535)

我有一个用@cacheable注解的方法。如果在方法中捕获了异常,我希望清除缓存。但是,缓存似乎加载在清除缓存的行之后执行的方面中。因此,当在方法中捕获异常时,即使清除了缓存,空字符串结果仍保留在缓存中。
我应该从哪里清除缓存?

@Cacheable("myCache") 
public String myMethod() {
    String result="";
    try {
        result = doSomething();
    } catch (Exception e) {
        cacheManager.getCache("myCache").clear();
    }
    return token;
}
btxsgosb

btxsgosb1#

好的-注解上有一个属性可以使用。以下示例来自(http://websystique.com/spring/spring-4-cacheable-cacheput-cacheevict-caching-cacheconfig-enablecaching-tutorial/)
除非:条件缓存,应用于方法的返回值。项将被缓存,除非满足“除非”中提到的条件。请注意,条件适用于方法的返回值。#结果是指方法的返回值。

@Cacheable(value="products", key="#product.name", condition="#product.price<500", unless="#result.outofstock")
public Product findProduct(Product product){
..
return aproduct;
}

所以你可以 unless="#result.length() == 0" 并在错误情况下或不希望缓存结果的任何其他时间返回空字符串。

相关问题