工程使用spring缓存,但是发现再返回空的情况下也被缓存了,导致有数据后再查询还是返回被缓存的空值。
解决办法:使用unless参数
unless英文是除非的意思,意思就是 除了这个条件成立都缓存,又或者这个条件成立就不缓存
举例:
@ResponseBody
@Cacheable(value = "custom_analyze", keyGenerator = "cacheKeyGenerator", condition = "#noCache!=true",
unless = "#result.totalCount == 0")
@CachePut(value = "custom_analyze", keyGenerator = "cacheKeyGenerator", condition = "#noCache==true")
public Object sheetData(HttpServletRequest request,@Param("noCache")Boolean noCache) {
BaseRet br = new BaseRet();
Map<String, Object> paramMap = RequestParamUtil.getRequestParam(request,true);
br.setAddData(mainService.getSheetData(paramMap, br));
br.setSuccess(true);
br.setMsg("查询成功!");
return JsonpFactory.parse(request.getParameter("callback"), br);
}
我这个方法返回的是json字符串,而json返回的格式为:
如果totalCount为0的我就不缓存,unless参数里的 #result为方法的返回值,所以判断
result.totalCount==0 即可,返回条数为0则不缓存