Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable ehCache (3.x) in SpringMVC (5.x) project

In our project we use the ehcache 2.x and now we want to migrate to 3.x but somehow I fail tremendously. In 2.x we have the configuration in ehcache.xml. To what I read is that I need to change the content as well when using 3.x.

But first of all I have no clue how to wire the Cache by itself. I have

@EnableCaching
@Configuration
public class CacheConf {
  @Bean
  public CacheManager cacheManager() {
    final CacheManagerBuilder<org.ehcache.CacheManager> ret = CacheManagerBuilder.newCacheManagerBuilder();
    ret.withCache("properties", getPropCache());
    ret.withCache("propertyTypes", getPropCache());
    return (CacheManager) ret.build(true);
  }
....

But this configuration I get a java.lang.ClassCastException: org.ehcache.core.EhcacheManager cannot be cast to org.springframework.cache.CacheManager which means that I cannot set the ehcache properly.

Note: In 2.x we configured different types of caches, more or less due to the expiration period - and since other object types are stored therein.

Hints to get it running, cause I didn't find a working sample with Spring 5 and ehcache 3.x? Best would be a config without xml!

like image 586
LeO Avatar asked Oct 19 '25 05:10

LeO


1 Answers

The Ehcache CacheManager isn't a Spring CacheManager. This is why you get the ClassCastException.

Ehcache 3 is JSR107 (JCache) compliant. So Spring will connect to it using that.

You will find an example here and a simpler one in Spring Boot petclinic.

If I take your example, you will do something like

@EnableCaching
@Configuration
public class CacheConf {
    @Bean
    public CacheManager cacheManager() {
        EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider();

        Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
        caches.put("properties", getPropCache());
        caches.put("propertyTypes", getPropCache());

        DefaultConfiguration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader());
        return new JCacheCacheManager(provider.getCacheManager(provider.getDefaultURI(), configuration));
    }

  private CacheConfiguration<?, ?> getPropCache() {
    // access to the heap() could be done directly cause this returns what is required!
    final ResourcePoolsBuilder res = ResourcePoolsBuilder.heap(1000);
    // Spring does not allow anything else than Objects...
    final CacheConfigurationBuilder<Object, Object> newCacheConfigurationBuilder = CacheConfigurationBuilder
        .newCacheConfigurationBuilder(Object.class, Object.class, res);
    return newCacheConfigurationBuilder.build();
  }
}
like image 128
Henri Avatar answered Oct 21 '25 19:10

Henri