admin管理员组

文章数量:1599543

今天在测试@Cacheable注解关于condition和unless时,做一个数据库查询操作,如果查询得到的对象为空,则不讲其放入缓存中

condition如下

    @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"发现竟然所有对象都不进入缓存了,每次操作都会经过数据库

后来改使用unless解决了这个问题

    @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" 可以不将空对象放入缓存中,解决了此问题

后来查阅后发现SpEL语言中:

condition对入参进行判断,符合条件的放入缓存,不符合的不缓存

condition能使用的只有#root和参数,不能使用返回结果


unless是对出参进行判断,符合条件的不缓存,不符合的放入缓存,

而unless是可以使用#result的

本文标签: 注解SpringBootcacheablecondition