The method below will give a set of keys for cached objects, but here, if you add a cache with keys, it will be easy to get (if you add a list of objects directly to the cache, this will not work).
In addition, I used GuavaCache in the cache manager, as shown below.
@Bean public CacheManager cacheManager() { SimpleCacheManager simpleCacheManager = new SimpleCacheManager(); GuavaCache userLabCache = new GuavaCache("yourCacheName", CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build()); simpleCacheManager.setCaches(Arrays.asList(userLabCache)); return simpleCacheManager; }
Then it will return a list of keys in the form of objects, then you will get the keys and you can iterate over the keys and get objects one by one from the cache.
Autowire Springboot CacheManager in your class
@Autowired CacheManager cacheManager;
Below is the code to get all the keys.
public Set<Object> getAllCachedUserLabKeys() { Set<Object> keys = null; try { GuavaCache cache = (GuavaCache) cacheManager.getCache("yourCacheName"); if (cache != null) { ConcurrentMap<Object, Object> cachedMap = cache.getNativeCache().asMap(); keys = cachedMap.keySet(); } } catch (Exception e) { LOGGER.error("Unknown exception occured while fetchting all cached User Labs..!", e); } return keys; }
source share