HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring Boot / Spring boot ehcache 2 example

Spring boot ehcache 2 example

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 !!

Sourcecode download

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Spring Boot 2 Tutorial

  • Spring Boot – Introduction
  • Spring Boot – Starter parent
  • Spring Boot – Starter templates
  • Spring Boot – Multi-module project
  • Spring Boot – Annotations
  • Spring Boot – Auto configuration
  • Spring Boot – AOP
  • Spring Boot – Logging
  • Spring Boot – DevTools
  • Spring Boot – WAR Packaging
  • Spring Boot – REST API
  • Spring Boot – CRUD
  • Spring Boot – OAuth2
  • Spring Boot – Testing
  • Spring Boot – RestTemplate
  • Spring Boot – Thymeleaf
  • Spring Boot – Hibernate
  • Spring Boot – DataSource
  • Spring Boot – Error Handling
  • Spring Boot – Caching
  • Spring Boot – Retry
  • Spring Boot – BasicAuth
  • Spring Boot – H2 Database
  • Spring Boot – Ehcache 3.x
  • Spring Boot – Gson
  • Spring Boot – RMI
  • Spring Boot – Send Email
  • Spring Boot – Interview Questions

Spring Boot Tutorial

  • Spring Boot – CommandLineRunner
  • Spring Boot – Configure Jetty
  • Spring Boot – Tomcat Default Port
  • Spring Boot – Context Root
  • Spring Boot – SSL [https]
  • Spring Boot – Get all loaded beans
  • Spring Boot – PropertyEditor
  • Spring Boot – @EnableScheduling
  • Spring Boot – Jersey
  • Spring Boot – SOAP Webservice
  • Spring Boot – SOAP Client
  • Spring Boot – JMSTemplate
  • Spring Boot – REST APIs
  • Spring Boot – JSP View
  • Spring Boot – Actuator endpoints
  • Spring Boot – Role Based Security
  • Spring Boot – RSS / ATOM Feed
  • Spring Boot – Ehcache 2.x

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)