Working With Spring Boot and Hazelcast (Distributed Cache)
How to create a simple Spring Boot application, using Hazelcast as a Distributed Cache. This can help improve database performance.
Join the DZone community and get the full member experience.Join For Free
Hazelcast provides central and predictable scaling of applications via in-memory access to frequently used data and across an elastically scalable data grid. These techniques both reduce the query load on databases and help improve application speed.
Spring Boot is often used to create stand-alone, production-grade Spring-based Applications that you can 'just run.'
Let us create a simple Spring Boot application with Hazelcast as a Distributed Cache.
Below is an implementation of a local cache for better performance.
Here, when a request is made from an application, if that data is available in the cache, then we don’t have to make a call to the database, or if data is not available in the cache, then a request is made to the database.
We deploy the application as a distributed system, as below, for better load balancing.
Here is the implementation of a simple spring boot application.
First, we make changes in the pom file by adding a Hazelcast dependency, as below:
We also add a plugin where the entry point to the application is provided in the distributed system. Since
DoctorApplication is the main class it is added in the plugin as below:
POM file should look like below:
We will be using IMAP provided by hazelmap as the cache. IMAP implements a map interface. Below is the Spring Boot application where beans use IMAP for caching in configuring the Hazelcast instance.
Since we are making use of IMAP we need to serialize the object. Here, Doctor object should be serializable.
Let us create a controller and auto-wire
Nice! We have made all the necessary changes.
Let us start the application with the below commands:
java -Dserver.port='8081' -jar boot-hazel-0.0.1-SNAPSHOT.jar
java -Dserver.port='8082' -jar boot-hazel-0.0.1-SNAPSHOT.jar
java -Dserver.port='8083' -jar boot-hazel-0.0.1-SNAPSHOT.jar
Let's say we have started 3 instances at 3 different ports (8081, 8082, 8083).
When a doctor's details are stored via the 8081 port application, then the same object can be retrieved from the 8083 port or 8082 port application from the cache and it does not need to make a call to the database.
After the above implementation, the architecture looks like below:
Here all the nodes are synchronized and the same date will be retrieved when requested from any of the JVM with better performance and better load balance.
Opinions expressed by DZone contributors are their own.