Spring缓存-发生错误时不要缓存

pri*_*lia 4 java spring caching

我正在使用春季缓存,我的问题是:

如果结果是错误并且下一个请求可能很好,我该如何控制缓存?

例:

@Cacheable("mycache")
public  ResponceBO getBigObject(String id) throws Exception {

    boolean isError = false;

    ***   load big object from other service,  can be loaded with errors  ***
    isError = true;

    if(error){
       responceBO.setError(true);
    }

    return responceBO;
}
Run Code Online (Sandbox Code Playgroud)

如果发生错误,我不想缓存对象,该怎么办?

M. *_*num 5

我建议阅读参考指南中的条件缓存部分。基本上,只需指定一个unless表达式即可防止缓存。(result占位符仅可用于该unless语句,而不能用于该condition语句。

@Cacheable("mycache", unless="#result.error")
public  ResponceBO getBigObject(String id) throws Exception { ... }
Run Code Online (Sandbox Code Playgroud)

应该做到的。

  • 如果是或不是 and `unless=#result == null || #result.error`之类的东西,你可以尝试使用`or`而不是`||`。 (2认同)