Getting Started with Hazelcast IQueue as a Messaging Service
Hazelcast is an open source in-memory data grid based on Java. We can use Hazelcast’s in- memory shared queue as a message broker without the need for an external application such as Kafka, MQ etc. Note, the hazelcast queue has a scaling limitation, for additional information read here
Step one:
Paste the following dependency to your pom.xml:
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>3.8.1</version>
</dependency><dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-client</artifactId>
<version>3.8.1</version>
</dependency>
If you are working in AWS you will need to add the following as well:
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-cloud</artifactId>
<version>3.6.1</version>
</dependency>
Step two:
Create a hazelcast instance:
private def createInstance(groupName : String): HazelcastInstance ={
val conf: Config = new Config
conf.getGroupConfig.setName(groupName)
Hazelcast.newHazelcastInstance(conf)
}
If you are working in an AWS env you will need to configure the hazelcast instance differently using ClientAwsConfig, but this will not be covered here.
Step three:
Create the Message case class:
case class MyMessage(messageData : String)
Step four:
Create/Get the message queue:
val QUEUE_NAME : String = “MyQueue”private val queue : IQueue[MyMessage] = hazelcastInstance.getQueue[MyMessage](QUEUE_NAME)
Step five:
Add a message to the queue, with a timeout of 30 seconds:
val message = MyMessage(“my data”)
val wasSuccessful = queue.offer(message, 30, TimeUnit.SECONDS)
You can then handle unsuccessful additions to the queue.
Step six:
Create a message listener and register it to the the queue:
Class MessageListener() extends ItemListener[MyMessage]{
override def itemAdded(p1: ItemEvent[MyMessage]): Unit = {
val messageFromQueue : MyMessage = queue.take()
//handle message here
} override def itemRemoved(p1: ItemEvent[BuildDataRefreshTask]): Unit = {
…
}
}
Register the message listener to the queue
val messageListener = new MessageListener()
queue.addItemListener(messageListener,false)
Summary
Hazelcast distributed queue can be used as a light weight messaging broker without the need for an external messaging app. Use with caution if scaling is an issue.
Photo by Frederick Tubiermont on Unsplash