本文介绍了Spring Boot Cache中的Caffeine Cache:获取所有缓存的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Caffeine Cache库用于Spring Cache.有没有办法获取所有缓存的密钥?

I'm using Caffeine Cache library for Spring Cache. Is there a way to get all the cached keys?

我当前的应用程序处理的是近实时数据,流为:

My current application works on a near-realtime data, with the flow as :

Cache Updater Thread (无论用户请求如何,它以固定的间隔运行)中,我需要获取Cache中当前的所有键,并从Db&中获取最新的数据.然后使用 @CachePut 更新缓存.

In the Cache Updater Thread(which runs at a fixed interval, irrespective of the user request), I need to get all the keys currently in the Cache, fetch their latest data from Db & then use @CachePut to update the cache.

推荐答案

Yo可以注入CacheManager并从中获取本机缓存.

Yo can inject CacheManager and obtain native cache from it.

@AllArgsConstructor
class Test {
  private CacheManager cacheManager;

  Set<Object> keys(String cacheName){
    CaffeineCache caffeineCache = (CaffeineCache) cacheManager.getCache(cacheName);
    com.github.benmanes.caffeine.cache.Cache<Object, Object> nativeCache = caffeineCache.getNativeCache();
    return nativeCache.asMap().keySet();
  }

}

当然,您应该添加一些类转换检查.

Of course you should add some class casting checks.

这篇关于Spring Boot Cache中的Caffeine Cache:获取所有缓存的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:47