Spring Boot Caching With Ehcache3

Dependencies

Add the following to your pom

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

Cache configuration

Keep the following ehcache.xml under src/main/resources

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns='http://www.ehcache.org/v3'>

	<persistence directory="${java.io.tmpdir}" />

	<!-- Default cache template -->
	<cache-template name="default">
		<expiry>
			<tti unit="hours">4</tti>
			<!-- <ttl unit="minutes">2</ttl> -->
		</expiry>
		<listeners>
			<listener>
				<class>com.org.lob.support.LoggingTaskCacheListener</class>
				<event-firing-mode>ASYNCHRONOUS</event-firing-mode>
				<event-ordering-mode>UNORDERED</event-ordering-mode>
				<events-to-fire-on>CREATED</events-to-fire-on>
				<events-to-fire-on>EXPIRED</events-to-fire-on>
				<events-to-fire-on>REMOVED</events-to-fire-on>
				<events-to-fire-on>UPDATED</events-to-fire-on>
			</listener>
		</listeners>
		<resources>
			<heap unit="MB">10</heap>
			<offheap unit="MB">50</offheap>
			<disk persistent="true" unit="GB">1</disk>
		</resources>
		<!-- 
		<heap-store-settings>
			<max-object-graph-size>2000</max-object-graph-size>
			<max-object-size unit="kB">5</max-object-size>
		</heap-store-settings>
		-->
	</cache-template>

	<!-- Cache configurations -->
	<cache alias="books" uses-template="default" >
		<key-type>java.lang.String</key-type>
		<value-type>com.org.lob.project.repository.entity.Book</value-type>		
	</cache>

	<cache alias="files" uses-template="default" >
		<key-type>java.lang.String</key-type>
		<value-type>java.lang.String</value-type>		
	</cache>

</config>

Spring Boot Config

Add the following to your application.properties

# Cache
spring.cache.jcache.config=classpath:ehcache.xml

Add the following spring boot config

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {
	
}

Start Caching

@Component
@CacheConfig(cacheNames = "books")
public class SimpleBookRepository implements BookRepository {
	
	@Cacheable
	@Override
	public Book getByIsbn(String isbn) {
		simulateSlowService();
		return new Book(isbn, "Some book");
	}

	// Don't do this at home
	private void simulateSlowService() {
		try {
			long time = 3000L;
			Thread.sleep(time);
		} catch (InterruptedException e) {
			throw new IllegalStateException(e);
		}
	}
}

@Component
@CacheConfig(cacheNames = "files")
public class SimpleFileRepository implements FileRepository {

	private static final Logger LOGGER = LoggerFactory.getLogger(SimpleFileRepository.class);

	@Override
	@Cacheable
	public String load(String project) {
		return asString(new FileSystemResource(project));
	}

	@Override
	@CachePut
	public String reLoad(String project) {
		return asString(new FileSystemResource(project));
	}

	private String asString(Resource resource) {
        try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) {
            return FileCopyUtils.copyToString(reader);
        } catch (IOException e) {
        	LOGGER.error("Error Proessing ", e);
            throw new UncheckedIOException(e);
        }
    }
}

Source Code

Download the source code from github