In this blog post I will show how to run hazelcast on Apache Karaf or Apache ServiceMix and I will provide an example application that creates a hazelcast instance, deploys the hazelcast monitoring web application and adds a couple of shell commands on Apache Karaf.

Finally, I will create a Hazelcast Topic using blueprint and we will create a clustered echo command using that topic.

For all of the above I will provide the full source so that you can try it yourself.

Hazelcast & OSGi
According to the hazelcast website hazelcast is not yet OSGi ready (it is still in the TODO list). However, I found that versions 1.9.x are ready enough to get you going. In this post I will use the current trunk of hazelcast source (1.9.3-SNAPSHOT) for which I have created a couple of patches for the web-console and for some other minor issues.

Hazelcast Instance as an OSGi service

Even though that Hazelcast requires zero configuration, I found it best to create a Hazelcast instance using Spring, pass the desired configuration and finally expose the instance as an OSGi service.

In the snippet above I am using a minimal configuration which only set the credentials of the Hazelcast. Hazelcast has no dependencies so the only thing required is the hazelcast bundle and the hazelcast monitoring war (if you wish to have access to the web console). From the Karaf shell you can just type:

Building a distributed collection using the Blueprint
To create a distributed collection with hazelcast all you need is an instance and a unique String identifier that will be used to uniquely identify the collection. Since we already have created an instance and exposed it as an OSGi service the rest are pretty easy:

We will use this distributed topic to build a distributed echo command (A command that will print messages in the console of all nodes). Now we need two simple things:

A listener on that topic that will listen for messages and display them

A shell command that will put messages to the topic.

A listener could be as simple as this:

This is a simple pojo that contains a topic and acts as MessageListner on that topic. For each message added to the topic this listener displays it to the standard output. We could add this pojo to our blueprint xml

What's left to be done is to create the command that will actually display the message that is added to the topic.

Putting it them all together
We can now start two karaf nodes either on the same machine or on separate machines in the same network, deploy hazelcast and its monitoring and finally deploy the instance, the topic and the commands as we did so far.