Search code examples
hibernatespring-bootehcachecodahale-metrics

How do I configure Dropwizard/CodaHale metrics for ehCache in Spring Boot application?


So here's my problem. My Spring Boot application uses Hibernate/JPA and ehCache for 2nd level caching. I'd like to instrument ehCache with Dropwizard/Coda-Hale metrics, but I'm not really sure how to do it. If I were manually creating Cache instances, then it's simple. You just use a decorator as shown here. But since it's Spring/Hibernate, I don't have control over the caches. Any ideas how I would go about setting this up?


Solution

  • Well I believe I've finally figured it out. It turns out that adding in the Spring JavaConfig for cacheManager that returned Spring classes ehCacheCacheManager could still be used to access the underlying ehCache classes and decorate them. Here's how I got it to work

    @Bean
    public EhCacheCacheManager ehCacheCacheManager() {
        final EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager(ehCacheManagerFactoryBean().getObject());
        net.sf.ehcache.CacheManager cacheManager = ehCacheCacheManager.getCacheManager();
        String[] cacheNames = cacheManager.getCacheNames();
        for (String cacheName : cacheNames) {
            Cache cache = cacheManager.getCache(cacheName);
            cacheManager.replaceCacheWithDecoratedCache(cache, InstrumentedEhcache.instrument(metricRegistry, cache));
        }
        return ehCacheCacheManager;
    }
    
    
    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
    
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
    
        cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cacheManagerFactoryBean.setShared(true);
    
        return cacheManagerFactoryBean;
    }