BACKGROUND
The documentation on the web regarding Ehcache 3.x configuration using Spring is rather lacking. There is apparently a very distinct difference in Spring Java-based configuration between Ehcache 2.x vs Ehcache 3.x.
Spring + Ehcache 2.x
Dependency:-
<dependency>
<groupid>net.sf.ehcache</groupid>
<artifactid>ehcache</artifactid>
<version>2.10.3</version>
</dependency>
Spring configuration:-
@Configuration
@EnableCaching
class Config {
@Bean
CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheManager())
}
@Bean(destroyMethod = 'shutdown')
net.sf.ehcache.CacheManager ehCacheManager() {
CacheConfiguration cacheConfiguration = new CacheConfiguration(
name: 'person',
maxEntriesLocalHeap: 5,
timeToLiveSeconds: 5
)
net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration()
config.addCache(cacheConfiguration)
return new net.sf.ehcache.CacheManager(config)
}
}
Spring + Ehcache 3.x
Dependency:-
<dependency>
<groupid>org.ehcache</groupid>
<artifactid>ehcache</artifactid>
<version>3.3.1</version>
</dependency>
<dependency>
<groupid>javax.cache</groupid>
<artifactid>cache-api</artifactid>
<version>1.0.0</version>
</dependency>
Spring configuration:-
import org.ehcache.config.CacheConfiguration
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.ehcache.core.config.DefaultConfiguration
import org.ehcache.expiry.Duration
import org.ehcache.expiry.Expirations
import org.ehcache.jsr107.EhcacheCachingProvider
import org.springframework.cache.annotation.EnableCaching
import org.springframework.cache.jcache.JCacheCacheManager
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import javax.cache.CacheManager
import javax.cache.Caching
import java.util.concurrent.TimeUnit
@Configuration
@EnableCaching
class Config {
@Bean
JCacheCacheManager jCacheCacheManager() {
return new JCacheCacheManager(cacheManager())
}
@Bean(destroyMethod = 'close')
CacheManager cacheManager() {
CacheConfiguration cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(
Object,
Object,
ResourcePoolsBuilder.heap(5)).
withExpiry(Expirations.timeToLiveExpiration(new Duration(5, TimeUnit.SECONDS))).
build()
Map<string, cacheconfiguration=""> caches = ['person': cacheConfiguration]
EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider()
DefaultConfiguration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader())
return provider.getCacheManager(provider.getDefaultURI(), configuration)
}
}
Leave a Reply