6

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.

imAmanRana
  • 123
  • 1
  • 3
  • 9
  • Can you please reference me with a good example for the implemantation. I am on my way to implement the same. – Einstein_AB May 04 '20 at 10:41
  • Hello @Einstein_AB, I'll suggest you to go through the spring cache [doc](https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-caching.html). If you are specifically using Caffeine cache, you can refer to [this](https://www.javadevjournal.com/spring-boot/spring-boot-with-caffeine-cache/) example. – imAmanRana May 06 '20 at 02:11

2 Answers2

13

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.

  • 1
    As a follow up to this. It's important to note that CaffeineCache Impliments Cache, so this casting is natural. Any other cache type implementing Cache should be castable this way. – Michael Rountree Feb 24 '21 at 18:39
0

You can return keyset by using asMap().keySet() method as follows.

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

class Test{
private Cache<String,String> testCache;
Test(){
 testCache = Caffeine.newBuilder().expireAfterWrite( 3000, TimeUnit.SECONDS).build();
}
     
// return keys as a set
public Set<String> getCacheKeySet(){
return testCache.asMap().keySet();
}
oshadhi
  • 33
  • 7