Leveraging Hazelcast for Distributed Caching in Spring Boot Microservices

Sajith vijesekara
3 min readJan 4, 2025

--

Application response time is a critical factor when building high-performance applications. To optimize this time, we can use caching strategies.

Assume we have an inventory management service that connects to the database. for high availability, we have two instances of API servers.

API service with multiple instances

There are main two types of cache strategies that can be followed in microservices.

  1. Distributed Cache
  2. Local Cache Strategies

In the distributed architecture, there are two types of distributed cache available.

  1. Centralized Cache
  2. Embedded Cache

For example, we can use Redis as a centralized cache provider, since the cache instance will be available as a single instance it will synchronize the data between microservices.

centralized cache in microservices

In the example above, we can integrate any type of cache provider to offer a centralized cache for applications. This approach is suitable for large-scale, enterprise-grade architectures, though maintaining a centralized cache introduces additional costs to the system.

The next approach is to use an application-level cache. However, if there are multiple instances, we cannot guarantee that user requests will be routed to the same instance in future requests. As a result, all cache instances need to be synchronized.

distributed cache in microservices

Hazelcast

Hazelcast is a widely used open-source distributed caching provider, particularly popular in microservices architectures. In this guide, I will outline the steps to configure a Spring Boot application with Hazelcast.

  1. Add Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-spring</artifactId>
<version>5.3.1</version>
</dependency>

2. Add Hazelcast configs file

@Configuration
public class HazelcastConfig {

private final Logger logger = LoggerFactory.getLogger(getClass());

@Bean
public HazelcastInstance hazelcastInstance() {
HazelcastInstance instance = Hazelcast.newHazelcastInstance();
instance.getConfig().addMapConfig(new MapConfig("inventory-api").setTimeToLiveSeconds(5));
LogListener listener = logEvent -> logger.info(logEvent.getLogRecord().getMessage());
LoggingService loggingService = instance.getLoggingService();
loggingService.addLogListener(Level.INFO, listener);
return instance;
}

@Bean
public ClientConfig clientConfig() {
ClientConfig cfg = ClientConfig.load();
cfg.setClusterName("inventory-api-cluster");
return cfg;
}
}

3. Enable cache in the spring boot application.

@EnableCaching
public class ApiServiceApplication {

public static void main(String[] args) {
SpringApplication.run(ApiServiceShrApplication.class, args);
}

}

5. Can use spring cache annotations to implement cache features

@Cacheable(value = "products", key = "#category")
@Override
public List<ProductSummaryDto> getProductsByCategory(String category) {
// your logic
}

Once we start the service, it will launch embedded Hazelcast instances. If multiple instances are running, you can observe that all the Hazelcast instances synchronize properly.

connect two embedded Hazelcast instances

Thank you for taking the time to read this blog! Your feedback and suggestions are invaluable in helping us improve the content and make it more useful for our readers. Please feel free to share your thoughts and comments below. Your input is greatly appreciated!

--

--

Sajith vijesekara
Sajith vijesekara

Written by Sajith vijesekara

Technical Lead. Passionate about cloud computing & web security | Freelance Mobile Developer| CKAD | AWS Community Builder 🇱🇰

No responses yet