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

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

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

  1. @Cacheable("myCache")
  2. public String myMethod() {
  3. String result="";
  4. try {
  5. result = doSomething();
  6. } catch (Exception e) {
  7. cacheManager.getCache("myCache").clear();
  8. }
  9. return token;
  10. }
btxsgosb

btxsgosb1#

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

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

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

相关问题