【问题标题】:How can I update cache with CachePut?如何使用 CachePut 更新缓存?
【发布时间】:2019-02-25 15:53:55
【问题描述】:

我的@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

【问题讨论】:

  • 您能否详细说明您要缓存的内容以及使用什么键?如果您正在更新/添加任何实体,如果您正在缓存此列表,则可能必须逐出列表。

标签: java spring spring-cache


【解决方案1】:

应该使用@CacheEvict 而不是@CachePut。 它对我有用:

 @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;
        }

【讨论】:

    猜你喜欢
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多