Paul Taylor
Paul Taylor

Reputation: 13130

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.

Upvotes: 4

Views: 2583

Answers (3)

Raju
Raju

Reputation: 289

We can use this piece of code to fetch the cachenames

for (String cacheName : cacheManager.getRuntimeConfiguration().getCacheConfigurations().keySet()) {
            System.out.println(cacheName);
        }

Upvotes: 1

Ludovic Orban
Ludovic Orban

Reputation: 416

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);
}

Upvotes: 1

Henri
Henri

Reputation: 5731

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

Upvotes: 1

Related Questions