Hazelcast with Spring Boot

Anil Kurmi
Microservices Architecture
2 min readApr 9, 2023

Hazelcast is a distributed computation and storage platform for consistently low-latency querying, aggregation and stateful computation against event streams and traditional data sources. It allows you to quickly build resource-efficient, real-time applications. You can deploy it at any scale from small edge devices to a large cluster of cloud instances.

Add the following dependencies to your Spring Boot Server project’s pom.xml file:

<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-spring</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
@Configuration
public class HazelcastConfig {
@Bean
@Profile("local")
public Config eurekaConfig() {
var mapConfig=new MapConfig()
.setName("default")
.setTimeToLiveSeconds(30);

var config = new Config();
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(true);
config.setClusterName("localhost");
config.setInstanceName("localInstance");
config.addMapConfig(mapConfig);
return config;
}
}

Inside your Spring Boot Client Application add following maven dependencies and annotate the methods or classes that you want to cache with the Spring Cache annotations, for example:

<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-client</artifactId>
<version>{hazelcast-version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-spring</artifactId>
<version>{hazelcast-version}</version>
</dependency>

-- Other dependencies e.g. spring boot cache
@Bean
public HazelcastInstance hazelcastInstance() {
ClientConfig config = new ClientConfig();
config.getNetworkConfig().addAddress("remote-address");
return HazelcastClient.newHazelcastClient(config);
}

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

@Autowired
private HazelcastInstance hazelcastInstance;

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

@Service
public class MyService {

@Cacheable("myCache")
public Object getCachedObject(String key) {
// retrieve object from database or other source
return object;
}

@CachePut("myCache")
public void updateCachedObject(String key, Object object) {
// update object in database or other source
}

@CacheEvict("myCache")
public void evictCachedObject(String key) {
// remove object from database or other source
}
}

That’s it folks!

Happy Coding!

--

--