如何使用CachePut更新缓存?

时间:2018-09-21 09:07:26

标签: java spring spring-cache

我的@Cacheable方法具有下一个签名:

@Component
public class UpcomingFilter implements Filter<Entity> {

    @Cacheable(value = {"upcoming"})
    @Override
    public List<Entity> filter(int limit) {
       //retrieve from repository
    }
}

此过滤器使用重排性,以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中使用了“键”一词,但是如何添加

@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

1 个答案:

答案 0 :(得分:0)

应该使用@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;
        }