今天在测试@Cacheable注解关于condition和unless时,做一个数据库查询操作,如果查询得到的对象为空,则不讲其放入缓存中
@Cacheable(value = "userCache", key = "#id", condition="#result != null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
使用condition="#result != null"发现竟然所有对象都不进入缓存了,每次操作都会经过数据库
@Cacheable(value = "userCache", key = "#id", unless="#result == null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
unless=“#result == null” 可以不将空对象放入缓存中,解决了此问题
这里是引用condition对入参进行判断,符合条件的放入缓存,不符合的不缓存
condition能使用的只有#root和参数,不能使用返回结果unless是对出参进行判断,符合条件的不缓存,不符合的放入缓存, 而unless是可以使用#result的
参考博客