How to Integrate Hazelcast with Spring Boot?

Overview

In today’s software application, it is essential to manage the data, especially when your system is getting scaled. Hazelcast is one of the distributed in-memory data grids that works with distributed systems and clusters of nodes. Hazelcast allows the distributed map with Spring Boot, which manages the distributed cache, session, and various cloud patterns that can be easily implemented.

In this article, we will explain the step-by-step, how to integrate Hazelcast with Spring Boot framework.

What is Hazelcast?

Hazelcast is open-source in-memory data computing platform, which enables distributed data structure, and computing framework. By using of Hazelcast you can frequently access and cache the data, it improve the application performance and ensure that data available on multiple nodes.

Benefit of Integrate Hazelcast with Spring Boot Framework

When you develop the Spring Boot application, in the backend we are required to manage the data. Hazelcast provides the features to manage the data in distributed nodes and improve the application performance.

  • Distributed Caching: Hazelcast store the data into multiple distributed nodes, it improves the application performance.
  • Distributed Sessions: Hazelcast store the sessions that ensure the sessions are accessible.
  • Clustered Data Structure: By using of Hazelcast distributed data structure, the application can be scaled up horizontally.
Integrate Hazelcast with Spring Boot

Pre-requisite

  • Java 8 or higher
  • Knowledge of spring boot
  • Hazelcast cluster should be installed and running
  • Basic Knowledge of Hazelcast
  • An IDE (Intellij, Eclipse or similar)
  • Should be aware of database persistence, you can visit the below articles to learn more about persistence.

Understanding of Hazelcast Mapstore
Understanding of Hazelcast MapLoader
How to connect Database Persistence with Hazelcast Hikari connection pooling?

Integrate Hazelcast with Spring Boot Project Structure

You can create a new Spring Boot project using Spring Initializr or your preferred IDE.

Project structure

Hazelcast Dependency with Spring Boot

Make sure to include the following dependencies:

  • Spring Boot Starter Cache: For caching support in Spring Boot.
  • Hazelcast: The Hazelcast core library.
  • Spring Boot Starter Data Hazelcast: For integrating Hazelcast with Spring Data.
<!-- Spring Boot Starter Data Hazelcast -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-hazelcast</artifactId>
</dependency>

<!-- Spring Boot Starter for cache enable -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
   <groupId>com.hazelcast</groupId>
   <artifactId>hazelcast-spring</artifactId>
   <version>5.5.0</version>
</dependency>

Hazelcast Spring configuration

You can configure Hazelcast as the cache provider in your Spring Boot application. Declare the @Bean for hazelcastInstance(), mapConfig() and cacheManage().

@Configuration
@EnableCaching
public class CacheConfig {
    @Autowired
    private HazelcastInstance hazelcastInstance;

    @Bean
    public CacheManager cacheManager() {
        return new HazelcastCacheManager(hazelcastInstance);
    }
}

@Configuration
public class HazelcastConfig {
    @Bean
    public HazelcastInstance hazelcastInstance() {
        ClientConfig config = new ClientConfig();
        ClientNetworkConfig clientNetworkConfig = config.getNetworkConfig();

        Properties properties = new Properties();
        properties.put("hazelcast.instance", "dev");
        properties.put("hazelcast.clustername", "javaTechARC");
        properties.put("hazelcast.password", "");

        clientNetworkConfig.setSSLConfig(new SSLConfig()
                .setEnabled(false)
                .setProperties(properties));
        clientNetworkConfig.setAddresses(List.of("localhost:5701"));
        config.setClusterName("dev");
        config.setInstanceName("javaTechARC");

        return HazelcastClient.newHazelcastClient(config);
    }

    @Bean
    public Config mapConfig() {
        Config config = new Config();

        // Configure a map with a specific name
        MapConfig mapConfig = new MapConfig();
        mapConfig.setName("javaTechARC_Map");
        mapConfig.setTimeToLiveSeconds(300); // TTL Config

        config.addMapConfig(mapConfig);

        return config;
    }
}

Use Hazelcast cache in service

For demo we created simple service HazelcastDemoService class, where hazelcastDemo() can use to put and get the data data from IMap. But another method demonstrate that you can use the @Cacheable annotation on methods that you want to cache by using CacheManager.

@Component
public class HazelcastDemoService {
    public final HazelcastInstance hazelcastInstance;

    public HazelcastDemoService(HazelcastInstance hazelcastInstance) {
        this.hazelcastInstance = hazelcastInstance;
    }

    /**
     * Consume this demo method from controller or any other layer as required
     */
    public String hazelcastDemo() {
        IMap&lt;String, String&gt; testMap = hazelcastInstance.getMap("javaTechARC_Map");
        System.out.println("Size before add : "+testMap.size());

        testMap.put("1", "JavaTechARC3i");
        System.out.println("Size add add : "+testMap.size());
        System.out.println("Map Data : "+testMap);

        IQueue&lt;String&gt; iQueue = hazelcastInstance.getQueue("employee_queue");
        iQueue.add("Test");
        iQueue.remove("Test");

        return "Success";
    }

    @Cacheable("demoCache")
    public String cacheableDemo(String key) {
        // Simulate a time-consuming operation
        try {
            Thread.sleep(3000); // Simulate delay
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        return "demo cache : "+key;
    }
}

Controller class DemoController for testing

You can expose the method to REST Controller and test the integration.

@RestController
@RequestMapping("/")
public class DemoController {
    public final HazelcastDemoService hazelcastDemoService;

    public DemoController(HazelcastDemoService hazelcastDemoService) {
        this.hazelcastDemoService = hazelcastDemoService;
    }

    @GetMapping("/demo")
    public ResponseEntity&lt;?&gt; demo() {
        return new ResponseEntity&lt;&gt;(hazelcastDemoService.hazelcastDemo(), HttpStatus.OK);
    }

    @GetMapping("/demo")
    public ResponseEntity&lt;?&gt; demoCacheable() {
        return new ResponseEntity&lt;&gt;(hazelcastDemoService.cacheableDemo("demKey"), HttpStatus.OK);
    }
}

Best Practices for Hazelcast and Spring Boot Integration

  • Data Partitioning: Understand Hazelcast’s data partitioning model to optimize the performance and reliability of your distributed data structures.
  • Cluster Configuration: Ensure your Hazelcast cluster is correctly configured for production environments, with appropriate network settings and backup strategies.
  • Monitoring: Use the Hazelcast Management Center to monitor the performance and utilization.
  • Caching: Leverage Hazelcast’s caching capabilities to reduce database load and speed up your application.

Conclusion

Integrate Hazelcast with Spring Boot simplifies the process and provides a powerful tool for building robust applications. As organizations strive for agility and high availability, adopting Hazelcast alongside Spring Boot positions them for success in today’s competitive landscape. Embracing this combination can lead to more resilient and responsive applications, ultimately delivering a better experience for end-users. The above demo code available on github.

Happy Learning! 😊

 

2 thoughts on “How to Integrate Hazelcast with Spring Boot?”

  1. Pingback: How to Start Hazelcast Members and Client - A complete guide Java Tech ARC 3i

  2. Pingback: How to Start Hazelcast Members and Client Efficiently? - How To Integrate Java - Tech ARC 3i

Leave a Comment

Your email address will not be published. Required fields are marked *

Index
Scroll to Top