Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Spring Boot EhCache
3.
Features of Spring Boot EhCache
4.
Usage pattern of Spring Boot EhCache
4.1.
Cache-aside
4.2.
Read-through
4.3.
Write-through
4.4.
Write-behind
4.5.
Cache-as-SoR
5.
Spring Boot EhCache Storage Tiers
5.1.
1. On-Heap Store
5.2.
2. Off-Heap Store
5.3.
3. Disk Store
5.4.
4. Clustered Store
6.
Spring Boot EhCache Example
6.1.
Employee.java 
6.2.
EmployeeService.java :
6.3.
ehchache.xml 
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Spring Boot EhCache

Author Tanay kumar Deo
2 upvotes

Introduction

The Spring Boot's framework provides various Spring Boot cache providers, such as EhChache, Hazelcast, Redis, Caffeine, Infinispan, etc. These spring boot cache providers allow us to configure cache explicitly and transparently in an application.

This article will focus on Spring Boot EhCache for caching in our application. Spring Boot EhCache is an open-source, Java-based, and widely used Spring Boot cache provider. The current version of Spring Boot EhCahe is 3. 

Spring Boot EhCache

EhCache is an open-source, Java-based, and widely used Spring Boot cache provider. To use EhCache we will use the following dependency.

<dependency>  
      <groupId>org.ehcache</groupId>  
      <artifactId>ehcache</artifactId>  
</dependency>

 

EhCache uses a file called ehcache.xml. The spring-boot-starter-cache starter provides the EhCacheCacheManager. We can configure the ehchache.xml file by using the following property:

spring.cache.ehcache.config=classpath:config/demo-config.xml 

 

Features of Spring Boot EhCache

Spring Boot EhCache has many features. Some of them are listed below:

  • It is lightweightfast, Flexible, and Scalable.
  • With Spring Boot EhCache, we can perform Object Serialization.
  • It offers us cache eviction policies such as LFU (Least Frequently Used), LRU (Least Recently Used), and FIFO (First In First Out).
  • EhCache stores the cache in disk (SSD) and memory.
  • It depends on SLF4J (Simple Logging Facade for Java) for logging.
  • With EhCache, we have a complete implementation of JSR-107, and Jcache
  • EhCache supports distributed caching via JMS (Java Message Service) or JGroups and RMI (Remote Method Invocation).
  • It supports- fluent query language for distributed search.

Usage pattern of Spring Boot EhCache

The cache uses several access patterns. These are the following patterns used by Spring Boot EhCache:

  • Cache-aside
  • Read-through
  • Write-through
  • Write-behind
  • Cache-as-SoR (system-of-record)

Now, let's see each of these usage patterns in detail.

Cache-aside

Our application will first consult with the cache in the cache-aside usage pattern. If the data is available, it will return the data directly. Otherwise, it will fetch the data from the SoR (system-of-record), store it into the cache, and return it.

Read-through

The read-through usage pattern also copies the cache-aside usage pattern while reading the data from the cache. The main difference between the read-through and cache-aside usage patterns is that the read-through usage pattern implements a CacheEntryFactory interface. It also guides the cache on reading an object from the cache. It is better to wrap the Spring Boot EhCache instance with the instance of SelfPopulatingCache when using the read-through pattern.

Write-through

The write-through usage pattern also copies the cache-aside pattern while writing the data in the cache. The main difference between the write-through and cache-aside usage patterns is that the write-through pattern implements a CacheWriter interface. It configures the cache data for both write-through and write-behind patterns. It will write data to the SoR in the same thread as execution.

Write-behind

The write-behind usage pattern modifies the cache entries after some configurable delay. This delay may be in a few seconds, minutes, hours, a day, a week, or maybe for a long time. Simultaneously, it also queues the data to write later in the same thread of execution.

The data written using the write-behind usage pattern happens by creating a new transaction to commit the data in the SoR that is distinct from the primary transaction.

Cache-as-SoR

The cache-as-SoR usage pattern represents SoR writing and reading operations to the cache. This pattern reduces the responsibility of our application. It uses a combination of write and read patterns, including write-through, read-through, and write-behind. The cache-as-SoR reduces the difficulty level of the application.

Spring Boot EhCache Storage Tiers

Spring Boot EhCache provides us with various data storage areas, such as heap, disk, and clusters. We can configure a multi-storage cache (which uses more than one storage area). It is arranged and managed as Storage tiers.

These storage tiers are organized in preference order. The bottom-most storage tier is the authority tier, while the other tier is the caching tier (also known as nearer or near cache). The caching storage tier can have more than one storage area. The hottest/most used data is kept in the caching tier because it is generally faster than the authority tier. At the same time, other data is kept in the authority tier, which is slower than the caching tier.

In Spring Boot, We have four types of Storage tires supported by EhCache:

1. On-Heap Store

As the name suggests, it stores cache data in Java heap memory. It shares the storage with Java applications. It is fast because it uses a heap but has limited storage memory. The garbage collector scans the on-heap store.

2. Off-Heap Store

It uses the RAM (primary memory) to store cache data. The off-heap store is slower than the on-heap store because the cache data move to the on-heap store before use. It also has a limited size.

3. Disk Store

As the name suggests, it uses a disk to store cache data. It is much slower than the on-head store and off-heap store. The disk store has plenty of storage size.

4. Clustered Store

It stores cache data on the remote server. It is slower than the on-heap and off-heap storage. It may have a failover server that provides high availability.

Now that we have learned about different storage tires in EhChace. Let's understand how caching functions in any application via a diagram.

In the above diagram, we can see that:

  • One application may have one or more than one Cache Manager.
  • At a time, many cache data can be handled by one Cache Manager.
  • Caches can use more than one storage tier for storing cache data.
  • EhCache keeps the most recently used or most frequently used data in the faster tier, i.e., caching tier.

Spring Boot EhCache Example

In the article so far, we have learned about Spring Boot EhCache features, usage patterns, and supported storage tires. Now let's see an example of Spring Boot EhCache to understand its implementation.

First, let's create a Spring Boot project from Spring initializr.

SPRING INITIALIZR

As shown in the above image, we created a Spring project with group com.codingninjas, Artifact spring-boot-ehcache-example, and added the Spring Web dependency in our application. Now let's click on Generate button to download the file for our application.

Next, we need to add the spring-boot-starter-cache, ehcache 3, cache Api dependencies in our pom.xml file.

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

 

Now, we will configure our ehcache.xml file. It will tell the framework where to find the file. Open the application.properties file, and let's configure the EhCache with the following property.

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

 

After adding EhCache dependency and configuring our ehcache.xml, now, we will enable caching by using @EnableCaching annotation. To do so, we will write the following code in the SpringBootEhcacheExampleApplication.java file.

package com.codingninjas;  
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.boot.SpringApplication;   
import org.springframework.cache.annotation.EnableCaching; 
 
@SpringBootApplication  
 
@EnableCaching  
public class SpringBootEhcacheExampleApplication   {  


    public static void main(String[] args)   {  
            SpringApplication.run(SpringBootEhcacheExampleApplication.class, args);  
    }  
} 

 

Now, let's create a model class named Employee.java in the package com.codingninjas.model.

Employee.java 

In the class, we will define the following:

  • Variable empName, empID, empAge.
  • Generate getters and setters for the variable.
  • Create a constructor.

 

package com.codingninjas.model;  
public class Employee  {  


    private int empId;  
    private String empName;  
    private String empCity;  


    // Constructor  
    public Employee(int id, String name, String city)  {  
                    super();  
                    this.id = id;  
                    this.empName = name;  
                    this.empCity = city;  
            } 
  


            // Getters and Setters
    public String getEmpId() {  
          return empId;  
    }  


    public void setEmpId(String empId) {  
          this.empId = empId;  
    }  


    public String getEmpName()  {  
          return empName;  
    }  


    public void setEmpName(String Name)  {  
          this.empName = Name;  
    }  


    public int getEmpAge()   {  
          return empAge;  
    }  


    public void setSecondName(int age)  {  
          this.empAge = age;  
    }  


            @Override  
            public String toString()   {  
                   return "Employee [id=" + empId+ ", name=" + empName + ", city=" + empCity + "]";  
            } 


} 

 

We successfully created an employee model in the Employee.java class in the above code. Now, let's make the service class EmployeeService.java to add and manage cache data for employees.

EmployeeService.java :

This class is created under the com.codingninjas.service package. In this class, we will define the following:

  • Annotated the class with the @Service annotation.
  • Make an instance of HashMap.

 

package com.codingninjas.service;   
import java.util.HashMap;  
import org.springframework.stereotype.Service;  
import org.springframework.cache.annotation.Cacheable;  


@Service  
public class EmployeeService  {  
      static HashMap<Integer, Student> employee = new HashMap<>();  
      static   {  
            employee.put(1, new Employee(100, "Alex", "Berlin"));  
            employee.put(2, new Employee(101, "Tony", "Maxico"));  
            employee.put(3, new Employee(102, "Andrew", "Chicago"));  
      }  


      @Cacheable(cacheNames="demoCache", key="#id")  
      public Employee getEmplyeeByID(Integer id)   {  
            System.out.println("Fetching employees data from cache");  
            return student.get(id);  
      }  
} 

 

In the code above, we used @Cacheable annotation; we defined the name of the cache. All our data will be saved in this cache. We also defined the id as the key attribute of the @Cacheable annotation. The cache searches the employee based on id.

Finally, we will create the cache configuration file named ehcache.xml in our src/main/resources folder.

ehchache.xml 

<config  
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'  
xmlns='http://www.ehcache.org/v3'  
xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>  
    <ehcache>  
            <diskStore path="java.io.tmpdir" />  
            <defaultCache maxElementsInMemory="3000"   
                eternal="true"  
                overflowToDisk="false"   
                timeToLiveSeconds="1500" />  
                 <cache name="demoCache"   
                maxElementsInMemory="3000"  
                eternal="false"   
                overflowToDisk="false"   
                timeToLiveSeconds="15000" />  
    </ehcache>  
</config> 

 

We have successfully created all the required files for spring boot ehcache. So, let's run our application and see the output.

Fetching employees from cache  
[id=100, name=Alex, city=Berlin]  
[id=101, name=Tony, city=Mexico]  
[id=102, name=Andrew, city=Chicago]  

Must Read Spring Tool Suite

FAQs

1. What are the advantages of caching?

Ans. Caching has the following advantages:

  • Improve Application Performance
  • Reduce Database Cost
  • Reduce the Load on the Backend

 

2. What are the differences between EhCache and JCache?

Ans. JCache offers a minimal configuration file set that is ideal for the in-memory cache. But Ehcache supports more prominent and complex topologies and provides us with more features.

 

Key Takeaways

In this article, we learned about spring boot Ehcache. We implemented EhCache with a detailed example and learned how to use it in our application. We also learned how cache implementation could save us from many complex works.

Don't stop here. Check out the articles on STS DownloadSpring Boot Auto-configuration, Spring Boot AnnotationsSpring Boot Multi-Module ProjectSpring Boot Packaging, and Spring Boot CLI. You can also consider our Spring Boot Course to give your career an edge over others.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass