首页 > 解决方案 > 如何使用 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

标签: javaspringspring-cache

解决方案


相反,@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;
        }

推荐阅读