Apache ZooKeeper Java API Examples

posted on Nov 20th, 2016

Apache ZooKeeper

Apache ZooKeeper is a software project of the Apache Software Foundation. It is essentially a distributed hierarchical key-value store, which is used to provide a distributed configuration service, synchronization service, and naming registry for large distributed systems. ZooKeeper was a sub-project of Hadoop but is now a top-level project in its own right.

ZooKeeper's architecture supports high availability through redundant services. The clients can thus ask another ZooKeeper leader if the first fails to answer. ZooKeeper nodes store their data in a hierarchical name space, much like a file system or a tree data structure. Clients can read from and write to the nodes and in this way have a shared configuration service. Updates are totally ordered.

Pre Requirements

1) A machine with Ubuntu 14.04 LTS operating system.

2) Apache ZooKeeper 3.4.6 pre installed (How to set up single server ZooKeeper on Ubuntu 14.04)

ZooKeeper Java API

ZooKeeper has an official API binding for Java and C. The ZooKeeper community provides unofficial API for most of the languages (.NET, python, etc.). Using ZooKeeper API, an application can connect, interact, manipulate data, coordinate, and finally disconnect from a ZooKeeper ensemble.

ZooKeeper API has a rich set of features to get all the functionality of the ZooKeeper ensemble in a simple and safe manner. ZooKeeper API provides both synchronous and asynchronous methods.

Add these jar files to your java project

/usr/local/zookeeper/zookeeper-3.4.6.jar
/usr/local/zookeeper/lib/*.jar

Step 1 - Change the directory to /usr/local/zookeeper/bin

$ cd /usr/local/zookeeper/bin

Step 2 - Start zookeeper server

$ ./zkServer.sh start

ZooKeeperConnection.java

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
// import zookeeper classes

public class ZooKeeperConnection {
	// declare zookeeper instance to access ZooKeeper ensemble
	private ZooKeeper zoo;
	final CountDownLatch connectedSignal = new CountDownLatch(1);

	// Method to connect zookeeper ensemble.
	public ZooKeeper connect(String host) throws IOException,
			InterruptedException {
		zoo = new ZooKeeper(host, 5000, new Watcher() {
			public void process(WatchedEvent we) {
				if (we.getState() == KeeperState.SyncConnected) {
					connectedSignal.countDown();
				}
			}
		});
		connectedSignal.await();
		return zoo;
	}

	// Method to disconnect from zookeeper server
	public void close() throws InterruptedException {
		zoo.close();
	}
}

ZKCreate.java

Compile and execute ZKCreate.java

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

public class ZKCreate {
	// create static instance for zookeeper class.
	private static ZooKeeper zk;

	// create static instance for ZooKeeperConnection class.
	private static ZooKeeperConnection conn;

	// Method to create znode in zookeeper ensemble
	public static void create(String path, byte[] data) throws KeeperException,
			InterruptedException {
		zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE,
				CreateMode.PERSISTENT);
	}

	public static void main(String[] args) {
		// znode path
		String path = "/MyFirstZnode";
		// Assign path to znode
		// data in byte array
		byte[] data = "My first zookeeper app".getBytes();
		// Declare data
		try {
			conn = new ZooKeeperConnection();
			zk = conn.connect("localhost");
			create(path, data);
			// Create the data to the specified path
			conn.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			// Catch error message
		}
	}
}

Verify Znode

$ cd /usr/local/zookeeper/bin

$ ./zkCli.sh

get /MyFirstZnode

ZKExists.java

Compile and execute ZKExists.java

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZKExists {
	private static ZooKeeper zk;
	private static ZooKeeperConnection conn;

	// Method to check existence of znode and its status, if znode is available.
	public static Stat znode_exists(String path) throws KeeperException,
			InterruptedException {
		return zk.exists(path, true);
	}

	public static void main(String[] args) throws InterruptedException,
			KeeperException {
		String path = "/MyFirstZnode";
		// Assign znode to the specified path
		try {
			conn = new ZooKeeperConnection();
			zk = conn.connect("localhost");
			Stat stat = znode_exists(path);
			// Stat checks the path of the znode
			if (stat != null) {
				System.out.println("Node exists and the node version is "
						+ stat.getVersion());
			} else {
				System.out.println("Node does not exists");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			// Catches error messages
		}
	}
}

ZKGetData.java

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZKGetData {
	private static ZooKeeper zk;
	private static ZooKeeperConnection conn;

	public static Stat znode_exists(String path) throws KeeperException,
			InterruptedException {
		return zk.exists(path, true);
	}

	public static void main(String[] args) throws InterruptedException,
			KeeperException {
		String path = "/MyFirstZnode";
		final CountDownLatch connectedSignal = new CountDownLatch(1);
		try {
			conn = new ZooKeeperConnection();
			zk = conn.connect("localhost");
			Stat stat = znode_exists(path);
			if (stat != null) {
				byte[] b = zk.getData(path, new Watcher() {
					public void process(WatchedEvent we) {
						if (we.getType() == Event.EventType.None) {
							switch (we.getState()) {
							case Expired:
								connectedSignal.countDown();
								break;
							}
						} else {
							String path = "/MyFirstZnode";
							try {
								byte[] bn = zk.getData(path, false, null);
								String data = new String(bn, "UTF-8");
								System.out.println(data);
								connectedSignal.countDown();
							} catch (Exception ex) {
								System.out.println(ex.getMessage());
							}
						}
					}
				}, null);
				String data = new String(b, "UTF-8");
				System.out.println(data);
				connectedSignal.await();
			} else {
				System.out.println("Node does not exists");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

Set Data first

$ cd /usr/local/zookeeper/bin

$ ./zkCli.sh

set /MyFirstZnode Hello

Compile and execute ZKGetData.java

ZKSetData.java

Compile and execute ZKSetData.java

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

public class ZKSetData {
	private static ZooKeeper zk;
	private static ZooKeeperConnection conn;

	// Method to update the data in a znode. Similar to getData but without
	// watcher.
	public static void update(String path, byte[] data) throws KeeperException,
			InterruptedException {
		zk.setData(path, data, zk.exists(path, true).getVersion());
	}

	public static void main(String[] args) throws InterruptedException,
			KeeperException {
		String path = "/MyFirstZnode";
		byte[] data = "Success".getBytes();
		// Assign data which is to be updated.
		try {
			conn = new ZooKeeperConnection();
			zk = conn.connect("localhost");
			update(path, data);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

Verify Data

$ ./zkCli.sh

get /MyFirstZnode

ZKGetChildren.java

import java.util.List;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZKGetChildren {
	private static ZooKeeper zk;
	private static ZooKeeperConnection conn;

	// Method to check existence of znode and its status, if znode is available.
	public static Stat znode_exists(String path) throws KeeperException,
			InterruptedException {
		return zk.exists(path, true);
	}

	public static void main(String[] args) throws InterruptedException,
			KeeperException {
		String path = "/MyFirstZnode";
		// Assign path to the znode
		try {
			conn = new ZooKeeperConnection();
			zk = conn.connect("localhost");
			Stat stat = znode_exists(path);
			// Stat checks the path
			if (stat != null) {
				// “getChildren” method- get all the children of znode.It has
				// two args, path and watch
				List<String> children = zk.getChildren(path, false);
				for (int i = 0; i < children.size(); i++)
					System.out.println(children.get(i));
				// Print children's
			} else {
				System.out.println("Node does not exists");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

Create children znodes first

$ ./zkCli.sh

create /MyFirstZnode/myfirstsubnode Hi

create /MyFirstZnode/mysecondsubmode Hi

Compile and execute ZKGetChildren.java

ZKDelete.java

Compile and execute ZKDelete.java

import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.KeeperException;

public class ZKDelete {
	private static ZooKeeper zk;
	private static ZooKeeperConnection conn;

	// Method to check existence of znode and its status, if znode is available.
	public static void delete(String path) throws KeeperException,
			InterruptedException {
		zk.delete(path, zk.exists(path, true).getVersion());
	}

	public static void main(String[] args) throws InterruptedException,
			KeeperException {
		String path = "/MyFirstZnode";
		// Assign path to the znode
		try {
			conn = new ZooKeeperConnection();
			zk = conn.connect("localhost");
			delete(path);
			// delete the node with the specified path
		} catch (Exception e) {
			System.out.println(e.getMessage());
			// catches error messages
		}
	}
}

Verify

$ cd /usr/local/zookeeper/bin

$ ./zkCli.sh

ls /MyFirstZnode

Please share this blog post and follow me for latest updates on

facebook             google+             twitter             feedburner

Previous Post                                                                                          Next Post

Labels : ZooKeeper Single Server Setup   ZooKeeperMulti Server Setup   ZooKeeper Command Line Interface(CLI) usage