Deepak Deepak - 17 days ago 5x
Java Question

Good Zookeeper Tutorial with Java client

I was trying to use Zookeeper in our project. Could run the server..Even test it using .. All good..
But couldn't find a good tutorial for me to connect to this server using Java ! All I need in Java API is a method

public String getServiceURL ( String serviceName )

I tried --> Not good for me. : Sort of ok; but couldnt understand concepts clearly ! I feel it is not explained well..


Finally, this is the simplest and most basic program I came up with which will help you with ZooKeeper "Getting Started":

package core.framework.zookeeper;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZkConnect {
    private ZooKeeper zk;
    private CountDownLatch connSignal = new CountDownLatch(0);

    //host should be,,
    public ZooKeeper connect(String host) throws Exception {
        zk = new ZooKeeper(host, 3000, new Watcher() {
            public void process(WatchedEvent event) {
                if (event.getState() == KeeperState.SyncConnected) {
        return zk;

    public void close() throws InterruptedException {

    public void createNode(String path, byte[] data) throws Exception
        zk.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    public void updateNode(String path, byte[] data) throws Exception
        zk.setData(path, data, zk.exists(path, true).getVersion());

    public void deleteNode(String path) throws Exception
        zk.delete(path,  zk.exists(path, true).getVersion());

    public static void main (String args[]) throws Exception
        ZkConnect connector = new ZkConnect();
        ZooKeeper zk = connector.connect(",");
        String newNode = "/deepakDate"+new Date();
        connector.createNode(newNode, new Date().toString().getBytes());
        List<String> zNodes = zk.getChildren("/", true);
        for (String zNode: zNodes)
           System.out.println("ChildrenNode " + zNode);   
        byte[] data = zk.getData(newNode, true, zk.exists(newNode, true));
        System.out.println("GetData before setting");
        for ( byte dataPoint : data)
            System.out.print ((char)dataPoint);

        System.out.println("GetData after setting");
        connector.updateNode(newNode, "Modified data".getBytes());
        data = zk.getData(newNode, true, zk.exists(newNode, true));
        for ( byte dataPoint : data)
            System.out.print ((char)dataPoint);