0

i need toknow how to retrieve or where to see al data stored in my cache.

@Configuration
@EnableCaching
public class CachingConf {

    @Bean
    public CacheManager cacheManager() {
        Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.SECONDS)
                .maximumSize(1000);
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("hr");
        cacheManager.setCaffeine(cacheBuilder);
        return cacheManager;
    }

}
    private final CacheManager cacheManager;

    public CacheFilter(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        final var cache = cacheManager.getCache("hr");
    ......

I want to somehow see all data in my cache stored but the cache does not have get all or something like tht.Any advices guys?

1 Answers1

0

The spring cache abstraction does not provide a method to get all the entries in a cache. But luckily they provide a method to get the underlying native cache abstraction which is Caffeine cache in your case.

The Caffeine cache has a method called asMap() to return a map view containing all the entries stored in the cache.

So combining them together will give you the following :

var cache = cacheManager.getCache("hr");
com.github.benmanes.caffeine.cache.Cache<Object, Object> nativeCache = (com.github.benmanes.caffeine.cache.Cache<Object, Object>)cache.getNativeCache();
ConcurrentMap<K, V> map = nativeCache.asMap();

//Loop through the map here to access all the entries in the cache

Please note that it is a quick and effective fix but it will make your codes couple to Caffeine . If you mind , you can configure the spring cache to use JCache and configure JCache to use Caffeine cache (see this) . As JCache API implements Iterable<Cache.Entry<K, V>>, it allow you to iterate all of its entries :

var cache = cacheManager.getCache("hr");
javax.cache<Object, Object> nativeCache = (javax.cache<Object, Object>)cache.getNativeCache();
for(Cache.Entry<Object,Object> entry : nativeCache){
   //access the entries here.
}

Ken Chan
  • 84,777
  • 26
  • 143
  • 172