Open In App

Spring Boot – EhCaching

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:

EhCaching Storage Tiers are as follows:



EhCache Usage Patterns:

Access patterns used by EhCache are given below:



Points to remember while using EhCaching:

1. We need to add the following dependencies in pom.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:




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




    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:




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:




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.




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:




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 

Article Tags :