Learn to configure caching in spring boot application using ehcache 2.x. Learn to use annotation based cache config as well as manually updating cache with CacheManager.
1. Maven dependencies
In this example, we are using Spring boot version 1.5.13.RELEASE
. Older spring boot versions support ehcache 2.x
available under net.sf.ehcache package.
We need following dependencies to add caching capability.
- spring-boot-starter-cache
- ehcache (net.sf.ehcache)
- cache-api (javax.cache)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.company</groupId> <artifactId>SpringBootEhcache</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBootEhcache</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.13.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <skipTests>true</skipTests> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2. ehcache.xml
Spring boot automatically detects the presence of ehcache.xml
in classpath and configure it. Here we provide the cache names, expiration time etc.
Find the complete list of attributes in the ehcache documentation.
<ehcache> <diskStore path="java.io.tmpdir" /> <defaultCache maxElementsInMemory="2000" eternal="true" overflowToDisk="false" timeToLiveSeconds="1200" /> <cache name="employeeCache" maxElementsInMemory="2000" eternal="false" overflowToDisk="false" timeToLiveSeconds="10000" /> </ehcache>
3. @EnableCaching
It enables Spring’s annotation-driven cache management capability and enable support for interceptors when @Cacheable
annotated methods are invoked.
import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Configuration; @Configuration @EnableCaching public class CacheConfig { }
4. @Cacheable Annotation
To cache data which is returned from a method call, we can use @Cacheable annotation on the method. Use it’s attributes cacheNames
and key
to refer to cache and key attribute of cache entry.
import java.util.HashMap; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class EmployeeManager { static HashMap<Long, Employee> db = new HashMap<>(); static { db.put(1L, new Employee(1L, "Alex", "Gussin")); db.put(2L, new Employee(2L, "Brian", "Schultz")); } @Cacheable(cacheNames="employeeCache", key="#id") public Employee getEmployeeById(Long id) { System.out.println("Getting employee from DB"); return db.get(id); } }
5. CacheManager API
Sometimes we may want to use the caching in cases where using annotations might not seems perfect solution. In those cases, we can use org.springframework.cache.CacheManager and org.springframework.cache.Cache abstraction to access and utilize ehcache for adding and accessing cache entries.
To use CacheManager
, we must first autowire into a spring component and the use it’s getCache(name) method to get the cache instance by it’s name.
Once we have access to the cache, we can use it’s get()
and put()
methods to add and access cache entries.
//1 @Autowired private CacheManager cacheManager; //2 Cache cache = cacheManager.getCache("myCache"); cache.put(3L, "Hello"); String value = cache.get(3L).get();
6. Spring boot ehcache 2 example – demo
I am creating a model class Employee
whose instances will be cached.
import java.io.Serializable; public class Employee implements Serializable { private static final long serialVersionUID = 5517244812959569947L; private Long id; private String firstName; private String lastName; public Employee() { super(); } public Employee(Long id, String firstName, String lastName) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; } //Getters and setters @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; } }
Now in demo application class, I am testing the annotation based cache access using @Cacheable
annotation and manual cache access using CacheManager
.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Application { @Autowired private CacheManager cacheManager; @Autowired private EmployeeManager employeeManager; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { //This will hit the database System.out.println(employeeManager.getEmployeeById(1L)); //This will hit the cache - verify the message in console output System.out.println(employeeManager.getEmployeeById(1L)); //Access cache instance by name Cache cache = cacheManager.getCache("employeeCache"); //Add entry to cache cache.put(3L, "Hello"); //Get entry from cache System.out.println(cache.get(3L).get()); }; } }
Program output.
Getting employee from DB Employee [id=1, firstName=Alex, lastName=Gussin] Employee [id=1, firstName=Alex, lastName=Gussin] //Fetched from cache Hello
Drop me your questions related to this spring boot cache example using ehcache in comments.
Happy Learning !!
Leave a Reply