admin管理员组

文章数量:1599534

Spring Cache

@Cacheable的condition 属性能使用的SpEL语言只有#root和获取参数类的SpEL表达式,不能使用返回结果的#result 。所以 condition = "#result != null" 会导致所有对象都不进入缓存,每次操作都要经过数据库。

	@Cacheable(value = "userCache",key = "#id",condition = "#result != null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);
        return user;
    }

解决方案:
@Cacheable的unless属性可以使用#result表达式。
效果: 缓存如果有符合要求的缓存数据则直接返回,没有则去数据库查数据,查到了就返回并且存在缓存一份,没查到就不存缓存。

@Cacheable(value = "userCache",key = "#id",unless = "#result == null ")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
    User user = userService.getById(id);
    return user;
}

本文标签: 属性注解细节cacheSpring