Hazelcast Java Example
In the previous post we saw how to install, run and use Hazelcast – A Open Source In Memory Data Grid NoSQL based distributed cache, in this post we shall see Hazelcast Java Example.
1. Project Configuration
Lets create a simple maven Java Project with the below pom.xml file. Here we include two dependencies for Hazelcast one is for the server and the other is the client dependency.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.heapcode.hazelcast</groupId> <artifactId>hazelcast</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>hazelcast</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast</artifactId> <version>3.2</version> </dependency> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast-client</artifactId> <version>3.2</version> </dependency> </dependencies> </project> |
Below is the screenshot of the Project in Eclipse
2. Code a Java Server Program
Lets code a simple Server program which starts a Hazelcast instance, gets cache (creates one the first time) adds data to the cache and then prints the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.heapcode.hazelcast; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; public class HazelCastServer { public static void main(String[] args) { Config cfg = new Config(); HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg); Map<Integer, String> customerMap = instance.getMap("customers"); customerMap.put(1, "Bangalore"); customerMap.put(2, "Chennai"); customerMap.put(3, "Hyderabad"); System.out.println("Map Size:" + customerMap.size()); Set<Entry<Integer,String>> customers = customerMap.entrySet(); for (Iterator<Entry<Integer, String>> iterator = customers.iterator(); iterator.hasNext();) { Entry<Integer, String> entry = (Entry<Integer, String>) iterator.next(); System.out.println("Customer Id : "+ entry.getKey()+" Customer Name : "+entry.getValue()); } } } |
on running the above program we get the following output.
Note: Observe the below lines in the log which describes the number of nodes present in the distributed cache.
1 2 3 |
Members [1] { Member [192.168.1.121]:5701 this } |
Hazelcast supports various data structures such as Map, Queue etc, we shall consider Map for our example. The above program starts a server process that keeps running.
3. Starting the second node and adding/updating cache
Lets modify the same program above but with some changes to the cache such as updating an entry and adding two new entries.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.heapcode.hazelcast; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; public class HazelCastServer { public static void main(String[] args) { Config cfg = new Config(); HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg); Map<Integer, String> customerMap = instance.getMap("customers"); customerMap.put(3, "Mumbai"); customerMap.put(4, "Kolkata"); customerMap.put(5, "Delhi"); System.out.println("Map Size:" + customerMap.size()); Set<Entry<Integer,String>> customers = customerMap.entrySet(); for (Iterator<Entry<Integer, String>> iterator = customers.iterator(); iterator.hasNext();) { Entry<Integer, String> entry = (Entry<Integer, String>) iterator.next(); System.out.println("Customer Id : "+ entry.getKey()+" Customer Name : "+entry.getValue()); } } } |
On running the above program we get the below output.
Note: Observe the below lines in the log which describes the number of nodes now two, the current one and the previous one present in the distributed cache.
1 2 3 4 |
Members [2] { Member [192.168.1.121]:5701 Member [192.168.1.121]:5702 this } |
4. Code a Java Client Program
Lets code a simple Hazelcast client program which accesses the hazelcast server gets the cache and reads/updates it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.heapcode.hazelcast; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; public class HazelCastClient { @SuppressWarnings({ "deprecation" }) public static void main(String[] args) { ClientConfig clientConfig = new ClientConfig(); clientConfig.addAddress("127.0.0.1"); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); IMap<Object, Object> map = client.getMap("customers"); printMap(map); map.put(5, "New Delhi"); map.put(6, "Cochin"); printMap(map); } @SuppressWarnings("unchecked") private static void printMap(@SuppressWarnings("rawtypes") Map map){ System.out.println("Map Size:" + map.size()); Set<Entry<Integer,String>> customers = map.entrySet(); for(Iterator<Entry<Integer, String>> iterator = customers.iterator(); iterator.hasNext();) { Entry<Integer, String> entry = (Entry<Integer, String>) iterator.next(); System.out.println("Customer Id : "+ entry.getKey()+" Customer Name : "+entry.getValue()); } } } |
The above program basically accesses the server, gets the cache prints it, updates entry with key 5 and adds new entry and again prints the same.
Below is the output of the above program.
5. Check Distributed Property
Now lets check the distributed property of Hazelcast by stopping one of the server instances and verifying the data. On stopping one of the server instance below is the output seen in console of another server
1 2 3 4 5 6 7 8 9 10 11 12 |
INFO: [192.168.1.121]:5702 [dev] [3.2] Master Address[192.168.1.121]:5701 left the cluster. Assigning new master Member [192.168.1.121]:5702 this May 12, 2014 10:28:33 PM com.hazelcast.cluster.ClusterService INFO: [192.168.1.121]:5702 [dev] [3.2] Removing Member [192.168.1.121]:5701 May 12, 2014 10:28:33 PM com.hazelcast.cluster.ClusterService INFO: [192.168.1.121]:5702 [dev] [3.2] Members [1] { Member [192.168.1.121]:5702 this } May 12, 2014 10:28:35 PM com.hazelcast.partition.InternalPartitionService INFO: [192.168.1.121]:5702 [dev] [3.2] Partition balance is ok, no need to re-partition cluster data... |
We could see that the server instance running on port 5702 was stopped and the data shared on that node was rebalanced by the cluster.
Lets verify the data we added to the cluster by running the client program again, this time we just print and do nothing other than that.
We could see that there are 6 entries in all and no data was lost when one of the node on the cluster went down.
I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.
Hi manju,
I need some help regarding..saving database data in hazelcast instance ..with 2 hazelcast instsnces..my email id [email protected]
Hi Manju, can you please share the snippet for caching data from database as well.
Hi Abhinav,
Yes sure will do that.
Hi, good info, could please create one more post with advanced things like,
querieng, indexing etc.
with thanks
Ramesh
Hi Ramesh,
I will start adding the posts regarding the same soon.
Please add advanced tutorials for Hazelcast.
Hi Manju ,
I ran 2 programs with hazelcastserver and hazelcastnewserver as a different class, when i run these 2 classes they show their instance but not co-ordinate as like member[2] …. is there anything i am missing here ?…
Hi Manju ,
Can i store oauth2 token in Hazelcast and retrieve it ?
whether is it good way to store?
if please share me some sample snippet for that