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
@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) {
}
@CacheEvict ( "posts" )
public void deleteById(Integer postId) {
}
}
|
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
Similar Reads
Spring Boot Integration With MySQL as a Maven Project
Spring Boot is trending and it is an extension of the spring framework but it reduces the huge configuration settings that need to be set in a spring framework. In terms of dependencies, it reduces a lot and minimized the dependency add-ons. It extends maximum support to all RDBMS databases like MyS
4 min read
Spring Boot Integration With MongoDB as a Maven Project
MongoDB is a NoSQL database and it is getting used in software industries a lot because there is no strict schema like RDBMS that needs to be observed. It is a document-based model and less hassle in the structure of the collection. In this article let us see how it gets used with SpringBoot as a Ma
4 min read
Spring Boot MockMVC Example
Automated testing plays a vital role in the software industry. In this article, let us see how to do the testing using MockMvc for a Spring Boot project. To test the web layer, we need MockMvc and by using @AutoConfigureMockMvc, we can write tests that will get injected. SpringBootApplication is an
4 min read
Spring Boot Integration With PostgreSQL as a Maven Project
PostgreSQL is a user-friendly versatile RDBMS. This article lets us see how to integrate Spring Data JPA with PostgreSQL. There are some conventions to be followed while using PostgreSQL. We will cover that also. Working with PostgreSQL We can easily create databases and tables in that. The below sc
3 min read
Spring Boot JPA Sample Maven Project With Query Methods
In this article, let us see a sample maven project in Spring Boot JPA with Query methods. Spring Boot + JPA removes the boilerplate code and it will be enhanced much if we use query methods as well. Let us discuss this project with MySQL Connectivity for geeksforgeeks database and table name as "Con
6 min read
Spring Boot - Service Class Example for Displaying Response Codes and Custom Error Codes
Sometimes the error or status messages in webpages would be different from the default error message thrown by Tomcat (or any other server). An important reason for this is websites want to look unique in their approach to their users. So, a customized page for displaying status codes is always bett
6 min read
Spring Boot - Create a Custom Auto-Configuration
Usually, we might be taking a maven project or grade project for Spring Boot related projects. We will be adding the dependencies in pom.xml (in case of a maven project). In a spring application, Spring Boot auto-configuration helps to automatically configure by checking with the jar dependencies th
4 min read
Spring Boot - Consume Message Through Kafka, Save into ElasticSearch, and Plot into Grafana
In this article, we are going to make a program to produce some data using Kafka Producer which will consume by the Kafka Consumer and save into the elastic search DB, and later on, plot that JSON data into the Grafana dashboard. Start with configuring all the required software and tool. Requirement
7 min read
How to Implement AOP in Spring Boot Application?
AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of
10 min read
Spring Boot - AOP(Aspect Oriented Programming)
The Java applications are developed in multiple layers, to increase security, separate business logic, persistence logic, etc. A typical Java application has three layers namely they are Web layer, the Business layer, and the Data layer. Web layer: This layer is used to provide the services to the e
4 min read