Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a list of cache names in Ehcache 3

In Ehcache 2 I used

Cache<String, Release> releaseCache = cacheManager.getCacheNames();

But in Ehcache 3 although I have a CacheManager the getCacheNames() method does not exist.

like image 859
Paul Taylor Avatar asked Oct 20 '25 14:10

Paul Taylor


2 Answers

Yes indeed. It does not exist. You have these solutions:

  1. Do harsh reflection to get access to EhCacheManager.caches
  2. Use JSR-107 CacheManager.getCacheNames
like image 171
Henri Avatar answered Oct 22 '25 02:10

Henri


The only valid use-case for listing all caches by name is when that is for monitoring purposes. Ehcache 2 encouraged bad practices by tightly coupling caches to their name, which Ehcache 3 totally prevents.

If your use-case is to list caches for monitoring reasons, you should have a look at the not officially supported but nevertheless working monitoring API. There's a sample available over here: https://github.com/anthonydahanne/ehcache3-samples/blob/management-sample/management-sample/src/main/java/org/ehcache/management/sample/EhcacheWithMonitoring.java

Here's a brief example of how to use it to find out the existing cache names:

DefaultManagementRegistryService managementRegistry = new DefaultManagementRegistryService();

CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .using(managementRegistry)
    .withCache(...)
    .withCache(...)
    .build(true);

Capability settingsCapability = managementRegistry.getCapabilities().stream().filter(c -> "SettingsCapability".equals(c.getName())).findFirst().orElseThrow(() -> new RuntimeException("No SettingsCapability"));
for (Settings descriptor : settingsCapability.getDescriptors(Settings.class)) {
  String cacheName = descriptor.getString("cacheName");
  if (cacheName == null) {
    continue; // not a cache
  }
  System.out.println("cache : " + cacheName);
}
like image 35
Ludovic Orban Avatar answered Oct 22 '25 04:10

Ludovic Orban