How to use Zookeeper's java client API (5)

In the previous blog posts, we briefly introduced zookeeper, how to install a zookeeper cluster, and how to use the command line. In this blog post, we focus on how Zookeeper's java client API is used.

Create a session

Clients can connect to a ZooKeeper server by creating a Zookeeper (org.apache.zookeeper.ZooKeeper) instance. I recommend a blog post for everyone , the construction method and parameters are introduced in great detail, just take a look.

Let's take a look at the code that establishes the session.

public class CreateSession implements Watcher{

    private static ZooKeeper zookeeper;
    //创建一个与服务器的连接 需要(服务端的 ip+端口号)(session过期时间)(Watcher监听注册)  
    public static void main(String[] args) throws IOException, InterruptedException {

        zookeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSession());
        System.out.println(zookeeper.getState());
        Thread.sleep(Integer.MAX_VALUE);
    }

    private void doSomething(){
        System.out.println("do something");
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event:" + event);
        if(event.getState() == KeeperState.SyncConnected){
            System.out.println("ZooKeeper session established.");  
            doSomething();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

We need to pay attention to one point: ZooKeeper allows the client to register a Watcher listener with the server. When some specified events on the server trigger this Watcher, then an event notification will be sent to the specified client to realize the distributed notification function.

All APIs of zookeeper have two modes: synchronous and asynchronous. When using the asynchronous API, the client can set a callback for each operation. After the operation is executed, zookeeper will execute the corresponding callback.

The following will show you the difference between the two ways to create nodes.

Create nodes synchronously

public class CreateNodeSync implements Watcher{

    private static ZooKeeper zookeeper;
     //创建一个与服务器的连接 需要(服务端的 ip+端口号)(session过期时间)(Watcher监听注册) 
    public static void main(String[] args) throws IOException, InterruptedException {

        zookeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateNodeSync());
        System.out.println(zookeeper.getState());
        Thread.sleep(Integer.MAX_VALUE);
    }

    /**
     * 创建Znode
      * CreateMode:
      *     PERSISTENT (持续的,相对于EPHEMERAL,不会随着client的断开而消失)
      *     PERSISTENT_SEQUENTIAL(持久的且带顺序的)
      *     EPHEMERAL (短暂的,生命周期依赖于client session)
      *     EPHEMERAL_SEQUENTIAL  (短暂的,带顺序的)
      */
    private void doSomething(){
        try {
            String path = zookeeper.create("/node_2", "123".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("return path:" + path);

        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("do something");
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event:" + event);
        if(event.getState() == KeeperState.SyncConnected){
            doSomething();
        }
    }
}
  • 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
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

Create a node asynchronously

public class CreateNodeASync implements Watcher {

    private static ZooKeeper zookeeper;
     //创建一个与服务器的连接 需要(服务端的 ip+端口号)(session过期时间)(Watcher监听注册) 
    public static void main(String[] args) throws IOException, InterruptedException {

        zookeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateNodeASync());
        System.out.println(zookeeper.getState());
        Thread.sleep(Integer.MAX_VALUE);
    }
    private void doSomething() {
        zookeeper.create("/node_1", "123".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,
                new IStringCallback(), "this is content");

        System.out.println("do something");
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event:" + event);
        if (event.getState() == KeeperState.SyncConnected) {
            doSomething();
        }
    }

    static class IStringCallback implements AsyncCallback.StringCallback {

        @Override
        public void processResult(int rc, String path, Object ctx, String name) {

            System.out.println("rc:" + rc);
            System.out.println("path:" + path);
            System.out.println("ctx:" + ctx);
            System.out.println("name:" + name);

        }
    }
}
  • 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
  • 36
  • 37
  • 38

The results of their operation will no longer be shown to you, and the space will be relatively large. I have written synchronously and asynchronously for the API to add, delete, modify, and check the zookeeper nodes. You can download it at the link below.

download

这里写图片描述

Download address: http://download.csdn.net/detail/jiuqiyuliang/9758784

Summarize:

  • Here, the api adds, deletes, modifies and checks the zookeeper nodes, and there are synchronous and asynchronous methods.
  • zookeeper does not support recursive creation of child nodes (that is, if the parent node does not exist, it is not allowed to create child nodes)
  • zookeeper不支持递归删除(也就是说在父节点有子节点的情况下,不允许直接删除父节点)

下篇博文,我们进行zookeeper的实战部分。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325748105&siteId=291194637