Programmatically Configure Persistent Disk Storage with Ehcache and Spring Boot

I recently looked into enabling the persistent disk store feature of Ehcache in a Spring Boot application that was already using some of Ehcache’s other features. The cache was already being configured programmatically, so I was hoping to find a way to configure the disk store the same way. And, I hoped to do that without having to add an XML configuration file.

Spring Boot and Ehcache

There are tons of examples and guides for how to set up Spring Boot caching with Ehcache, but nearly all of them use the XML configuration. Additionally, the ones that configure it programmatically don’t seem to use the disk store feature, which requires a directory to be configured for the persistent disk store to use.

I finally tracked down an example that got me unstuck, right in the middle of the Ehcache/JCache docs). However, I found it only after searching and reading through a ton of blog posts and Stack Overflow answers that all used the XML configuration. It’s a good reminder to thoroughly read the official docs before starting to search or use AI for an answer. It also didn’t help that ChatGPT wasn’t familiar with the latest version of Ehcache at the time.

My Solution

So in case someone else is looking for an example of how to programmatically configure Ehcache with a persistent disk store, in a Spring Boot application, here’s what I was able to get working.

@Bean
public org.springframework.cache.CacheManager cacheManager(
DefaultCacheEventListenerConfiguration eventLoggerConfig
) {
var config = CacheConfigurationBuilder.newCacheConfigurationBuilder(
Object.class, Object.class,
ResourcePoolsBuilder.newResourcePoolsBuilder()
.heap(500, EntryUnit.ENTRIES)
.offheap(1, MemoryUnit.GB)
.disk(3, MemoryUnit.GB, true)
)
.withService(eventLoggerConfig)
.build();

// A Map of all of the caches we want to create (just one in this example)
Map<String, CacheConfiguration<!--?,?-->> caches = Map.of("primary", config);

var cachingProvider = Caching.getCachingProvider();
var ehcacheProvider = (EhcacheCachingProvider) cachingProvider;

var configuration = new DefaultConfiguration(
caches,
ehcacheProvider.getDefaultClassLoader(),
new DefaultPersistenceConfiguration(new File("tmp/ehcache")));

return new JCacheCacheManager(
ehcacheProvider.getCacheManager(
ehcacheProvider.getDefaultURI(), configuration));
}

Hopefully, that will help if you’re trying to do the same thing. And, if you have any suggestions for how to improve this, please let me know in the comments!

Conversation

Join the conversation

Your email address will not be published. Required fields are marked *