Spring 缓存@CacheEvict 匹配列表中的键?

问题描述 投票:0回答:2

我正在使用 Spring 缓存并尝试通过键(id)列表逐出缓存。

@CacheEvict(value="cacheName",key=?, condition=? )
public void deleteByIds(List<Integer> ids){...}

我怎样才能做到这一点?

java spring spring-cache
2个回答
5
投票
  • @CacheEvict

注释表明一个方法(或类上的所有方法) 触发缓存逐出操作。

  • 缓存名称或值

存储方法调用结果的缓存名称。

  • 状况

用于使方法缓存有条件的表达式。

  • 钥匙

root.method、root.target 和 root.caches 分别用于对方法、目标对象和受影响的缓存的引用。

解决方案您的问题: 假设列表中的每个对象都被缓存到,例如cacheName =“entities”,并且对于键,您可以使用实体ID(它是整数值的字符串表示形式),您应该编写第二种方法来逐出缓存.

public void deleteByIds(List<Intiger> intigers){
 for(Intigier i : intigers){
  deleteEntity(i.toString());
 }
}

@CacheEvict(cacheName = "entities", key="entityId", condition="entityId!=null")
private void deleteEntity(String entityId){
 //processing : for ex delete from the database and also remove from cache
}

0
投票

可以通过CacheManager编写代码来清除缓存:

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class YourService {

    private final CacheManager cacheManager;
    private final YourRepository repository;

    public YourService(CacheManager cacheManager, YourRepository repository) {
        this.cacheManager = cacheManager;
        this.repository = repository;
    }

    public void evictCacheByIds(List<String> ids) {
        Cache cache = cacheManager.getCache("cacheName");
        for (String id : ids) {
            cache.evict(id);
        }
    }

    public void deleteByIdList(List<String> ids) {
        evictCacheByIds(ids);
        repository.deleteByIds(ids);
    }
}

您可以在这里查看:https://www.baeldung.com/spring-boot-evict-cache#2-using-cachemanager

© www.soinside.com 2019 - 2024. All rights reserved.