Open In App

Spring Boot – EhCaching

Improve
Improve
Like Article
Like
Save
Share
Report

EhCache is an open-source and Java-based cache. It is used to boost performance. Its current version is 3. EhCache provides the implementation of the JSR-107 cache manager. Features of EhCache are given below:

  • It is fast, lightweight, Flexible, and Scalable.
  • It allows us to perform Serializable and Object
  • It also offers cache eviction policies such as LRU, LFU, FIFO,

EhCaching Storage Tiers are as follows:

  • On-Heap Store: Java heap memory is used to store cache entries.
  • Off-Heap Store: It stores cache entries into primary memory (RAM).
  • Disk Store: It uses a disk to store cache entries.
  • Clustered Store: Remote server is used to store cache entries.

EhCache Usage Patterns:

Access patterns used by EhCache are given below:

  • Cache-aside: It can be used to read and update operations of data to and from the data store.
  • Cache-as-SoR (system-of-record): This pattern delegates SOR reading and writing activities to the cache so that the application code is absolved of this responsibility.
  • Read-through: This pattern copies the cache-aside pattern while reading data from the cache.
  • Write-through: This pattern copies the cache-aside pattern while writing data in the cache.
  • Write-behind: It is a caching strategy in which the cache layer itself connects to the backing database.

Points to remember while using EhCaching:

1. We need to add the following dependencies in pom.xml.

XML




<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.6.1</version></dependency>
<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.8.1</version>
</dependency>


2. Next we have to open the application.properties file and configure the EhCache by using the following property.

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

3. The @EnableCaching annotation triggers a post-processor that inspects every Spring bean for the presence of caching annotations methods that are public. If such an annotation is found, a proxy will be automatically created to intercept the method call and hence handle the caching behavior accordingly. We can use @EnableCaching annotation for enabling EhCaching as follows:

Java




@Configuration
// used for enabling  caching
@EnableCaching
public class CacheConfig {
}


4. This method-level annotation lets Spring Boot know that the value returned by the annotated method can be cached. Whenever a method marked with this @Cacheable is called, the caching behavior will be applied. In particular, Spring Boot will then check whether the method has been already invoked for the given arguments. This involves looking for a key that is generated using the method parameters by default. If no value is found in the cache related to the method for the computed key then the target method will be executed normally. Otherwise, the cached value will be immediately returned. @Cacheable comes with many parameters, but the easy way to use it is to annotate a method with the annotation and parameterize it with the name of the cache where the results will be stored. @Cacheable Annotation indicates that the result of invoking a method or all methods inside a class can be cached.

5. We need to create an hcache.xml file that contains the information related to the cache such as the name of the cache, no of the element in the memory, and time to live data in the cache, etc.

XML




    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
    monitoring="autodetect" dynamicConfig="true">
    <diskStore path="D:\\cache" />
  
    <cache name="cache1" 
        maxEntriesLocalHeap="10000"
        maxEntriesLocalDisk="1000" 
        eternal="false" 
        diskSpoolBufferSizeMB="20"
        timeToIdleSeconds="300" timeToLiveSeconds="600"
        memoryStoreEvictionPolicy="LFU" 
        transactionalMode="off">
        <persistence strategy="localTempSwap" />
    </cache>
  
</ehcache>


Example Project

An example of spring boot EhCaching is as follows.

Main class:

Java




import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
  
@SpringBootApplication
@ComponentScan("com.codippa")
public class CachingApplication {
  public static void main(String[] args) {
    SpringApplication.run(CachingApplication.class, args);
  }
}


Post class:

Java




public class Post {
  
    private Integer postId;
  
    private String title;
  
    public Post(Integer postId, String title)
    {
        this.postId = postId;
        this.title = title;
    }
  
    public Integer getPostId() { return postId; }
  
    public void setPostId(Integer postId)
    {
        this.postId = postId;
    }
  
    public String getTitle() { return title; }
  
    public void setTitle(String title)
    {
        this.title = title;
    }
}


Controller class:

This class maps the URL with the appropriate method.

Java




import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
  
@Controller
public class PostController {
  @Autowired
  PostService service; 
    
  @GetMapping("/posts/{id}")
  public @ResponseBody Post findById(@PathVariable("id") Integer postId) {
    return service.findById(postId);
  }
    
  @PostMapping("/updatepost")
  public void updatePost(Post post) {
    service.updatePost(post);
  }
    
  @DeleteMapping("/posts/{id}")
  public void deleteById(@PathVariable("id") Integer postId) {
     service.deleteById(postId);
  }
    
}


Service class:

The two caching annotations used in the code are explained as follows:

  • @CachePut: Cached objects are copies of original objects inside the database and should be identical to them. When the original object changes, then the cached object should be updated. This is done using the @CachePut annotation and is applied over the method that performs update operation.
  • @CacheEvict: This annotation is used to indicate a remote operation of the data from the cache and is applied to the method that deletes an object from the database

Java




import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
  
@Service
public class PostService {
   @Cacheable("posts")
   public Post findById(Integer postId) { 
      System.out.println("Fetching Post"); 
      return new Post(postId, "Demo post"); 
   
     
   @CachePut("posts")
   public void updatePost(Post post) {
      // update post
   }
   @CacheEvict("posts")
   public void deleteById(Integer postId) { 
     // delete post
   }
}


In order to test that caching is working, we have to hit URL, http://localhost:8080/posts/1, and look at the console. It should print the following output:

Output:

Fetching Post 


Last Updated : 13 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads