SpEL 和 Spring-cache:如何在 @CacheEvict#key 的表达式中访问第一个参数的属性?

2021-05-02 09:08:04 +08:00
 Newyorkcity
@Service
public class UserService {
    private final User[] database = new User[]{new User(0, "foo")};
    @Cacheable(cacheNames = "springboot:demo:cache", key = "#root.args[0]")
    public User query(Integer id) {
        return database[0];
    }

    @CacheEvict(cacheNames = "springboot:demo:cache", key = "#root.args[0].id")
    public void update(User user) {
        database[0] = user;
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {

    private static final long serialVersionUID = -1760350679406802739L;
    Integer id;
    String name;
}

我希望的效果:update 方法被执行后,之前由于 query 缓存在缓存里的(我用的是 redis )键被清除,但实际上并没有。。。

谢谢

549 次点击
所在节点    问与答
1 条回复
NULL2020
2021-05-02 11:08:40 +08:00
update 方法改成返回值 user,然后使用 key=result.id

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/774598

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX