【问题标题】:How to evict Cache based on Cache Name passed如何根据传递的缓存名称驱逐缓存
【发布时间】:2019-03-25 15:52:23
【问题描述】:

我在传递 List 的地方调用 fetchCatchAndClear 方法,它由缓存名称组成。有人可以帮助我如何迭代列表并根据来自字符串列表的缓存名称清除缓存。此外,如果列表为空,我应该清除所有存在的缓存。

【问题讨论】:

    标签: spring-boot caching spring-cache


    【解决方案1】:

    坚持org.springframework.cache.CacheManager 的相当简单的方法可能如下:

    List<String> cacheNames = List.of("aCache", "anotherCache"); // the list you are passing in
    CacheManager cacheManager = new SimpleCacheManager(); // any cache manager you are injecting from anywhere
    
    // a simple iteration, exception handling omitted for readability reasons
    cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
    

    驱逐所有缓存也很简单,只是你必须从同一个缓存管理器中查询相关的缓存名称:

    CacheManager cacheManager = new SimpleCacheManager();
    Collection<String> cacheNames = cacheManager.getCacheNames();
    
    cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
    

    如果您只想逐出单个缓存条目,您可以通过编程方式执行此操作,例如: cacheManager.getCache(cacheName).evict(cacheKey); 或基于注解的类似

    @CacheEvict(value = "yourCacheName", key = "#cacheKey")
    public void evictSingleCacheValue(String cacheKey) {
    }
    
    
    @CacheEvict(value = "yourCacheName", allEntries = true)
    public void evictAllCacheValues() {
    }
    

    【讨论】:

    • 请验证我是否可以写这种类型的东西 - public List fetchCache(List cacheManager.getCache(cacheName).clear()); } else{ 集合 cacheNames = cacheManager.getCacheNames(); cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear()); } 返回缓存名称;
    • 我不明白它在清除整个缓存和按特定名称清除方面有什么区别。让我知道上面的代码是否能解决我的目的。
    • 在这两种情况下使用注解@CacheEvict 怎么样
    • 是的,您评论中的代码与我提供的代码相同,我只是省略了周围的方法定义。你可以这样使用它。请记住,这两种变体都会清除整个缓存。如果您只想驱逐某些缓存条目,请使用cacheManager.getCache(cacheName).evict(cacheKey)。对于@CacheEvict,请查看我的更新答案。
    • 谢谢我添加了相同的代码,但现在我怀疑 .getCacheNames 是空的。我有一个类,我正在使用 Cacheable 注释给出缓存名称。这两者之间是否有任何联系,我的意思是 CacheManager 将如何识别 Cacheable 方法并从中收集信息。
    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2018-12-16
    • 2017-06-17
    • 1970-01-01
    • 2018-03-23
    • 2015-11-07
    • 2019-03-17
    相关资源
    最近更新 更多