Following are the steps to setup to
  • Hazelcast server
  • Put data in hazelcast
  • Retrieve data from hazelcast

Step 1 : Add the Hazelcast dependency


Step 2 : Initialize the Hazelcast Instance (Hazelcast Server)

Config config = new XmlConfigBuilder().build();
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config);

The above code will start the Hazelcast server with default settings. For more settings you can refer this blog.

Step 3 : Connect to Hazelcast server using a Hazelcast Client

Now to need to get a Hazelcast client to get and post data to the hazelcast server. Following is an example of how to get the hazelcast client.

ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setConnectionAttemptPeriod(24 * 60);
HazelcastInstance hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig);

So whenever you need to get or put data to hazelcast you need to pass the hazelcast client object to get a hazelcast reference.  Some points to note here are

  • Hazelcast client is static so that it does not create a new client for each request
  • setConnectionAttemptLimit() defines the number of attempts it makes to connect to the server before failing.
  • setConnectionAttemptPeriod() it defines the period for the next attempt to to find a member to connect to. It is the time to wait in mili seconds before another attempt.
  • setConnectionTimeout() Timeout value in millis for nodes to accept client connection requests, a zero value means wait until connection established or an error occurs.

Step 4 : Put some data in Hazelcast

Hazelcast always puts data in a collection using it via reference string, lets say we want to put some data in a Map then, we do it as follows

IMap<Long,String> map = hazelcastInstance.getMap("userMap");

In the above code,

  • userMap is the reference to the map stored in the hazelcast server.
  • IMap is the return type of the Map in Hazelcast.(IMap is an interface that extends ConcurrentMap and BaseMap interfaces. Thus you can also use the reference of Map to get the map from Hazelcast.)

Step 5 : Get data from Hazelcast 

IMap<Long,String> map = hazelcastInstance.getMap("userMap");
for(Long key : map.keySet())
System.out.println("key :: " + key + " value :: " + map.get(key));

The above code will print all the key value pairs in the userMap in the Hazelcast server.