Reputation: 10843
I'm currently writing some monitoring code for an app that's composed of lots of different little modules, many of which make use of EhCache. My goal is to gather statistics about hit ratios, cache contents, etc. from each cache in the app. However, I'm running into some trouble implementing this feature because enabling statistics is an opt-in feature in EhCache. I'm looking for a way to have statistics enabled for all caches in an automatic way so that developers maintaining the different modules don't have to always remember to enable them.
The closest thing I could find in the JavaDocs (but that still doesn't work is):
cacheManager.getDefaultCacheConfiguration().setStatisticsEnabled(true);
That method call enables statistics on the default cache only whereas the rest of the caches will not be affected.
Another thought I had was to wrap the CacheManager so as to intercept calls that create caches and automatically opt them in to statistics. Unfortunately, CacheManager is a class and not an interface, so such a solution would require lots of code and would be brittle--every time a public methods gets added/removed as EhCache evolves, I'd have to update my subclass.
Has anyone out there run into a similar problem? If so, how did you go about solving it? Many thanks...
Upvotes: 4
Views: 3783
Reputation: 1918
At some point once your caches are created you could 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'll want to add error checking.
If you have caches that are created dynamically, you can use a Cache Manager Event Listener (see the documentation). Basically you have to create a factory by extending CacheManagerEventListenerFactory
, and then create the actual listener by implementing CacheManagerEventListener
. The listener could 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 the factory with Ehcache you add this to ehcache.xml:
<cacheManagerEventListenerFactory class="com.example.cache.MyListenerFactory" properties=""/>
It could be important to note that if you set your default cache to have statistics enabled, then any cache you create dynamically will have statistics enabled by default unless whatever is creating the cache specifically turns it off.
Upvotes: 3