springspring-bootehcache-3

EhCache3 + Spring Boot 2 without XML


I'm stuck finding solution how to implement EhCache3 with Spring Boot 2. The problem is that in version 3 they changed package to org.ehcache and examples of xml-less configuration I found are for 2 version where you declare net.sf.ehcache.config. and I want to work with 3rd version.

 package com.jcg.example.ehcache_no_xml.config;

import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import net.sf.ehcache.Cache;
import net.sf.ehcache.config.CacheConfiguration;

@Configuration
public class EhCacheConfig {

    @Bean
    public EhCacheManagerFactoryBean cacheManager() {
        return new EhCacheManagerFactoryBean();
    }

    @Bean
    public EhCacheCacheManager testEhCacheManager() {
        // testEhCache Configuration - create configuration of cache that previous required XML
        CacheConfiguration testEhCacheConfig = new CacheConfiguration()
            .eternal(false)                     // if true, timeouts are ignored
            .timeToIdleSeconds(3)               // time since last accessed before item is marked for removal
            .timeToLiveSeconds(5)               // time since inserted before item is marked for removal
            .maxEntriesLocalHeap(10)            // total items that can be stored in cache
            .memoryStoreEvictionPolicy("LRU")   // eviction policy for when items exceed cache. LRU = Least Recently Used
            .name("testCache");

        Cache testCache = new Cache(testEhCacheConfig);

        cacheManager().getObject().addCache(testCache);
        return new EhCacheCacheManager(cacheManager().getObject());
    }
}

Is there any solution ho to create ehCache configuration propramaticaly with spring?


Solution

  • Ok, I will post my answer as I've resolved this problem along ago. I'm using Spring Boot and next dependencies:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.cache</groupId>
      <artifactId>cache-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.ehcache</groupId>
      <artifactId>ehcache</artifactId>
    </dependency>
    

    My cache config:

    @Configuration
    @EnableCaching
    public class CacheConfig {
    
        @Bean
        public JCacheCacheManager jCacheCacheManager() {
            return new JCacheCacheManager(cacheManager());
        }
    
        @Bean(value = "cacheManager")
        public CacheManager cacheManager() {
            CachingProvider provider = Caching.getCachingProvider();
            CacheManager cacheManager = provider.getCacheManager();
            List<String> cacheNames = Arrays.asList("myCacheName");
            cacheNames.forEach(cn -> cacheManager.createCache(cn, config()));
            return cacheManager;
        }
    
        private MutableConfiguration<SimpleKey, SiteIdSet> config() {
            return new MutableConfiguration<SimpleKey, SiteIdSet>()
                    .setTypes(SimpleKey.class, ClassWhichShouldBeCached.class)
                    .setStoreByValue(false);
        }
    
    }
    

    During the start a have a method which retrieves some values and then cache them:

    @Slf4j
    @Service
    @DependsOn("cacheManager")
    public class MyServiceImpl implements MyService {
    
        ommited ...
    
        @Override
        @Cacheable(cacheNames = "myCacheName")
        public Set<Integer> getSmth() {
            return callDb();
        }
    
        @Override
        @CachePut(cacheNames = "myCacheName")
        public Set<Integer> getSmth() {
            return callDb();
        }
    }
    

    I won't describe what this methods do, but they work with defined cache and populate and renew it when need.