Can I enable default statistics for all caches in EhCache?

I am currently writing monitoring code for an application consisting of many small modules, many of which use EhCache. My goal is to collect statistics on hit rates, cache content, etc. From each cache in the application. However, I encounter some problems with the implementation of this function, because the inclusion of statistics is a function of inclusion in EhCache. I’m looking for a way to automatically enable statistics for all caches so that developers supporting different modules do not always have to enable them.

The closest thing I could find in JavaDocs (but this still doesn't work):

cacheManager.getDefaultCacheConfiguration().setStatisticsEnabled(true); 

This method call includes default cache statistics, while the rest of the caches will not be affected.

Another thought was that I had to wrap the CacheManager in order to intercept the calls that create the caches and automatically select them for statistics. Unfortunately, CacheManager is a class, not an interface, so this solution will require a lot of code and will be fragile - every time when public methods are added / removed as EhCache develops, I will have to update my subclass.

Has anyone encountered a similar problem? If so, how did you decide to solve it? Thank you very much...

+4
source share
1 answer

At some point after creating your caches, you can do something like this:

 for (CacheManager manager : CacheManager.ALL_CACHE_MANAGERS) { for (String name : manager.getCacheNames()) { manager.getCache(name).getCacheConfiguration().setStatistics(true); } } 

Of course, you will want to add error checking.

If you have caches created dynamically, you can use the Cache Manager Event Listener (see the documentation ). Basically you need to create a factory by extending the CacheManagerEventListenerFactory , and then create the actual listener by running the CacheManagerEventListener . The listener might look like this:

 public class StatisticsEnabledCacheManagerListener implements CacheManagerEventListener { public void notifyCacheAdded(String cacheName) { CacheManager.getInstance().getCache(cacheName).getCacheConfiguration().setStatistics(true); } public void notifyCacheRemoved(String cacheName) {} } 

To register a factory with Ehcache, add it to ehcache.xml:

 <cacheManagerEventListenerFactory class="com.example.cache.MyListenerFactory" properties=""/> 

It is important to note that if you set the default cache to enable statistics, then any cache you create will have default statistics, unless creating a cache disables it.

+3
source

Source: https://habr.com/ru/post/1441869/


All Articles