java - 如何使用 CachePut 更新缓存?
问题描述
我的 @Cacheable 方法有下一个签名:
@Component
public class UpcomingFilter implements Filter<Entity> {
@Cacheable(value = {"upcoming"})
@Override
public List<Entity> filter(int limit) {
//retrieve from repository
}
}
该过滤器使用reporisoty,以limit作为分页参数并返回实体列表。将实体添加到系统时,我正在尝试更新缓存:
@CachePut(value={"upcoming", "popular", "recentlyAdded", "recommendations", "thisWeek", "topRated"})
public Entity addEntity(RequestDto dto, User user) {
//do work, create and save entity to repository
return entity;
}
但是在向系统添加新实体后,它不会更新。过滤器返回旧值。我看到了一些例子,其中 CachePut 和 Cacheable 使用了“key”这个词,但我该如何添加
@Cacheable(key="#entity.id")
过滤器签名?
更新
试图添加我的密钥:
@CachePut(value={"upcoming","popular", "recentlyAdded", "recommendations", "thisWeek", "topRated"},
key = "#root.target.FILTER_KEY", condition = "#result != null")
public Entity addEntity(RequestDto dto, User user) {
//do work, create and save entity to repository
return entity;
}
并将密钥添加到@Cacheable:
public static final String FILTER_KEY = "filterKey";
@Cacheable(value = {"recentlyAdded"}, key = "#root.target.FILTER_KEY")
@Override
public List<Entity> filter(int limit) {
比我得到的
java.lang.ClassCastException:com.java.domain.Entity 无法转换为 java.util.List
解决方案
相反,@CachePut 应该使用 @CacheEvict。这个对我有用:
@CacheEvict(value={"upcoming", "popular", "recentlyAdded", "recommendations", "thisWeek", "topRated"},
allEntries = true, condition = "#result != null")
public Entity addEntity(RequestDto dto, User user) {
//do work, create and save entity to repository
return entity;
}
推荐阅读
- javascript - 按一个属性值和/或另一个 AngularJS 过滤
- apache-beam - 如何使用 Beam 读取大型 CSV?
- docker - docker:创建 daemon.json 后 docker start 失败
- reactjs - React - 使用 Superagent 等待请求结束
- javascript - 展开/折叠表格数据
- javascript - 无法更改 Office UI React Dialog 版本的样式。5.56.0
- java - 在 android 中读取公共共享谷歌驱动器中的内容
- javafx - 如何正确构建 JavaFX 可样式化对象,可以是 GC
- java - 如何在okhttp中为拦截器设置延迟?
- c# - 清除 CollectionViewSource 的源时,WPF 接口变得无响应