在Ehcache 2中,我使用了
Cache<String, Release> releaseCache = cacheManager.getCacheNames();
但是在Ehcache 3中,虽然我有一个 CacheManager,但 getCacheNames() 方法不存在。
确实是的。它不存在。您有以下解决方案:
EhCacheManager.caches
CacheManager.getCacheNames
按名称列出所有缓存的唯一有效用例是出于监控目的。Ehcache 2 通过将缓存与其名称紧密耦合来鼓励不良做法,而 Ehcache 3 完全阻止了这种做法。
如果您的用例是出于监控原因列出缓存,您应该查看不受官方支持但仍在工作的监控 API。这里有一个示例:https ://github.com/anthonydahanne/ehcache3-samples/blob/management-sample/management-sample/src/main/java/org/ehcache/management/sample/EhcacheWithMonitoring.java
下面是一个简短的示例,说明如何使用它来找出现有的缓存名称:
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);
}