Caffeine Cache in Spring Boot Cache : Get all cached keys
Asked Answered
T

2

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.

Tetanus answered 28/1, 2020 at 5:10 Comment(2)
Can you please reference me with a good example for the implemantation. I am on my way to implement the same.Slinky
Hello @Einstein_AB, I'll suggest you to go through the spring cache doc. If you are specifically using Caffeine cache, you can refer to this example.Tetanus
D
14

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.

Declaim answered 28/1, 2020 at 6:38 Comment(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.Alejandroalejo
H
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();
}
Ha answered 31/7, 2021 at 20:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.