Search code examples
javaspring-bootcachingspring-cachecaffeine-cache

Caffeine Cache in Spring Boot Cache : Get all cached keys


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 :

enter image description here

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.


Solution

  • 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.