Caffeine Cache in Spring Boot Cache : Get all cached keys

与世无争的帅哥 提交于 2021-02-10 20:42:30

问题


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 :

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.


回答1:


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.



来源:https://stackoverflow.com/questions/59942462/caffeine-cache-in-spring-boot-cache-get-all-cached-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!