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.

Paul Taylor
  • 13,411
  • 42
  • 184
  • 351

2 Answers2

0

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
Henri
  • 5,551
  • 1
  • 22
  • 29
0

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);
}
Ludovic Orban
  • 396
  • 1
  • 6
  • Thanks but I dont understand why is it bad practise to get Cache by name then, what are you meant to get them by. – Paul Taylor Jul 26 '19 at 14:16
  • Getting a cache by name isn't bad practice. Using a cache's name for any other purpose is. – Ludovic Orban Jul 26 '19 at 15:29
  • Ludovic, what version of what jar files provide DefaultManagementRegistryService and Capability? I have ehcache 3.9 and hibernate 5.6.2.Final (.jar and sources), not seeing any references to those classes. – BodhiOne Feb 08 '22 at 19:10