Good Zookeeper Hello world Program with Java client
Asked Answered
F

5

5

I was trying to use Zookeeper in our project. Could run the server..Even test it using zkcli.sh .. 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 https://cwiki.apache.org/confluence/display/ZOOKEEPER/Index --> Not good for me.

http://zookeeper.apache.org/doc/trunk/javaExample.html : Sort of ok; but couldnt understand concepts clearly ! I feel it is not explained well..

Fidelafidelas answered 4/11, 2015 at 14:35 Comment(3)
Perhaps you should rephrase your question and avoid the use of "tutorial" ;-)Galan
I think that the question might be better rephrased by asking something like "What's Wrong with my Zookeeper Hello World Program?", with sample code in the question, and citing existing references like you currently have.Sonya
Don't know who in their right mind could negate this question. The question and the answer provided below by the same person helped me big time! Thank you Deepak!!!Gehlbach
F
30

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 127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002
    public ZooKeeper connect(String host) throws Exception {
        zk = new ZooKeeper(host, 3000, new Watcher() {
            public void process(WatchedEvent event) {
                if (event.getState() == KeeperState.SyncConnected) {
                    connSignal.countDown();
                }
            }
        });
        connSignal.await();
        return zk;
    }

    public void close() throws InterruptedException {
        zk.close();
    }

    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("54.169.132.0,52.74.51.0");
        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);
        }
        connector.deleteNode(newNode);
    }

}
Fidelafidelas answered 9/11, 2015 at 5:29 Comment(4)
Thanks for the example. It should be noted that you need to set the CountDownLatch to something other than 0 by default because the .await() will return once the latch reaches 0, which is the default value. If you set it to 1 when the event.getState() == KeeperState.SyncConnected it will kick the timer and after an interval of 1 reach 0, therefore return zk.Skiles
The host passed to connect in main method , is it wrong because there is no port mentioned.Momentarily
@Momentarily Zookeeper assumes you're using 2181.Jigaboo
this code is a deadlock. anyone succ? watcher.process executes after remove latch.awaitJoaquin
J
6

This post has almost all operations required to interact with Zookeeper. https://www.tutorialspoint.com/zookeeper/zookeeper_api.htm

  1. Create ZNode with data
  2. Delete ZNode
  3. Get list of ZNodes(Children)
  4. Check an ZNode exists or not
  5. Edit the content of a ZNode...
Joker answered 27/9, 2016 at 7:0 Comment(0)
M
3

This blog post, Zookeeper Java API examples, includes some good examples if you are looking for Java examples to start with. Zookeeper also provides a client API library( C and Java) that is very easy to use.

Zookeeper is one of the best open source server and service that helps to reliably coordinates distributed processes. Zookeeper is a CP system (Refer CAP Theorem) that provides Consistency and Partition tolerance. Replication of Zookeeper state across all the nods makes it an eventually consistent distributed service.

Missie answered 30/1, 2016 at 21:47 Comment(0)
C
3

This is about as simple as you can get. I am building a tool which will use ZK to lock files that are being processed (hence the class name):

package mypackage;

import java.io.IOException;
import java.util.List;

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

public class ZooKeeperFileLock {

  public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

    String zkConnString = "<zknode1>:2181,<zknode2>:2181,<zknode3>:2181";

    ZooKeeperWatcher zkWatcher = new ZooKeeperWatcher();
    ZooKeeper client = new ZooKeeper(zkConnString, 10000, zkWatcher);

    List<String> zkNodes = client.getChildren("/", true);

    for(String node : zkNodes) {
      System.out.println(node);
    }
  }

  public static class ZooKeeperWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {
    }

  }
Charleton answered 18/5, 2018 at 19:21 Comment(6)
Wow, why the downvote? This lists all nodes in the ZK Chroot directory and is about as simple as it gets. And how do I tell who did the downvote? Please clarify before just downvoting and moving on.Charleton
I gave u UPVOTE :). It was helpful for me. Some time people downvote without any explanation. I faced same.Womanlike
You did not actually use any of the files. I think your program just lists the root znodesQuasijudicial
yeah, I can edit. That was stub code that I was using for the actual program I was writing. Thanks for the head's up.Charleton
"Session establishment is asynchronous." You are not waiting for the connection to Zookeeper to be established.Mylo
Check the accepted answer and look at the role of the CountDownLatch.Mylo
F
2

If you are on AWS; now We can create internal ELB which supports redirection based on URI .. which can really solve this problem with High Availability already baked in.

Fidelafidelas answered 4/10, 2016 at 5:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.