Zookeeper client API

Time:2020-10-17

Introducing dependencies

<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.6</version>
</dependency>

Create connection

Interface description

ZooKeeperConstructor description

public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher);

public ZooKeeper(String connectString, 
                 int sessionTimeout,
                 Watcher watcher,
                boolean canBeReadOnly);

public ZooKeeper(String connectString, 
                 int sessionTimeout, 
                 Watcher watcher,
                 long sessionId, 
                 byte[] sessionPasswd);


ZooKeeper(String connectString, 
          int sessionTimeout, 
          Watcher watcher,
          long sessionId, 
          byte[] sessionPasswd, 
          boolean canBeReadOnly);

Parameter interpretation

connectString: ZK server list, strings separated by English commas,

For example: 127.0.0.1:2181127.0.0.1:2182127.0.0.1:2183;

sessionTimeout: session timeout in milliseconds. In a session cycle, ZK client and server check the validity of the connection by heartbeat. Once the heartbeat detection is not conducted within the session timeout time, the session fails.

watcher: ZK allows the client to pass in a watcher interface implementation class in the constructor as an event notification handler.

canBeReadOnly: in ZK cluster mode, if a cluster and more than half of the machines in the cluster lose network connection, the machine will no longer process client requests, including read and write requests. However, in some cases, a similar problem occurs. We hope that the machine can handle the read request. In this case, the mode is read-only.

sessionId、sessionPasswd: use sessionid and sessionpasswd to ensure reuse of session connection.

code

public class Test {
    //The process of creating a session between the client and the server is asynchronous. In other words, the client immediately returns after creating the session through the construction method. At this time, the connection is not fully established
    //After the real session is established, the ZK server will notify the client of an event. After receiving the notification, the client indicates that the connection is being established.
    //Used to wait for ZK server notification
    private static CountDownLatch latch = new CountDownLatch(1);

    private static ZooKeeper zk = null;
    //If there are multiple addresses, separate them with commas
    private static final String connString="127.0.0.1:2181";
    //Time out
    private static final int sessionTimeout = 2000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zk = new ZooKeeper(connString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
                if (Event.KeeperState.SyncConnected == event.getState()) {
                    latch.countDown();
                }
            }
        });
        latch.await();
        //Close ZK
        zk.close();
    }
}

Create node

Interface description

//Synchronous creation of nodes
public String create(final String path, byte data[], List<ACL> acl,
            CreateMode createMode);

//Create nodes asynchronously
public void create(final String path, byte data[], List<ACL> acl,
            CreateMode createMode,  StringCallback cb, Object ctx);

Parameter interpretation

String path:The path of node

byte data[]:Initialize node data

List acl:ACL permission of node

CreateMode createMode:Specify the node type, there are four types, as shown below

  1. CreateMode.PERSISTENT : persistent node, which will not be automatically deleted after the client connection is disconnected

  2. CreateMode.PERSISTENT_ Sequential: persistent sequential node

  3. CreateMode.EPHEMERAL : temporary node, which will be automatically deleted after the client connection is disconnected

  4. CreateMode.EPHEMERAL_ Sequential: temporary order node

StringCallback cb:Asynchronous callback function

Object ctx:Used to pass context information

Synchronous creation of nodes

public class Test {
    //The process of creating a session between the client and the server is asynchronous. In other words, the client immediately returns after creating the session through the construction method. At this time, the connection is not fully established
    //After the real session is established, the ZK server will notify the client of an event. After receiving the notification, the client indicates that the connection is being established.
    //Used to wait for ZK server notification
    private static CountDownLatch latch = new CountDownLatch(1);

    private static ZooKeeper zk = null;
    //If there are multiple addresses, separate them with commas
    private static final String connString="127.0.0.1:2181";
    //Time out
    private static final int sessionTimeout = 2000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zk = new ZooKeeper(connString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
                if (Event.KeeperState.SyncConnected == event.getState()) {
                    latch.countDown();
                }
            }
        });
        latch.await();

        //Temporary node: create an interface and return the path l of the node, such as / ZK test
        String path1 = zk.create("/zk-test", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("created path success : " + path1);

        //Temporary order node: it will automatically add a number after the node path, for example, the return value is / ZK test000000000 1
        String path2 = zk.create("/zk-test", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("created path success : " + path2);

        //Close ZK
        zk.close();
    }
}

Create nodes asynchronously

public class Test {
    //The process of creating a session between the client and the server is asynchronous. In other words, the client immediately returns after creating the session through the construction method. At this time, the connection is not fully established
    //After the real session is established, the ZK server will notify the client of an event. After receiving the notification, the client indicates that the connection is being established.
    //Used to wait for ZK server notification
    private static CountDownLatch latch = new CountDownLatch(1);

    private static ZooKeeper zk = null;
    //If there are multiple addresses, separate them with commas
    private static final String connString="127.0.0.1:2181";
    //Time out
    private static final int sessionTimeout = 2000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zk = new ZooKeeper(connString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
                if (Event.KeeperState.SyncConnected == event.getState()) {
                    latch.countDown();
                }
            }
        });
        latch.await();
        System.out.println(zk.getSessionId());
        System.out.println(zk.getSessionPasswd());
        /********************************************************************************************/

        //Persistent node: create an interface and return the path of the node without return value; node created asynchronously / ZK test
        zk.create("/zk-test",
                "".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT,
                new CallBack(),
                "PERSISTENT");

        //Persistent order node: it will automatically add a number after the node path. This method has no return value. After creation, the node is / ZK test seq0000000002
        zk.create("/zk-test-seq",
                "".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT_SEQUENTIAL,
                new CallBack(),
                "PERSISTENT_SEQUENTIAL");

        Thread.sleep(1000);

        //Close ZK
        zk.close();
    }

    static class CallBack implements AsyncCallback.StringCallback {
        * *
        @Override
        public void processResult(int code, String path, Object ctx, String name) {
            System.out.println("created success : code = " + code + ",path = " + path + ",ctx = " + ctx + ",name = " + name);
        }
    }
}

Get node data

Interface description

//Synchronous acquisition
public byte[] getData(String path, boolean watch, Stat stat);
public byte[] getData(final String path, Watcher watcher, Stat stat);

//Asynchronous acquisition
public void getData(String path, boolean watch, DataCallback cb, Object ctx);
public void getData(final String path, Watcher watcher,
            DataCallback cb, Object ctx);

Parameter interpretation

String path:The path of node

boolean watch:If watch is true, the state change of the znode will be sent to the watcher specified by the build zookeeper

Stat stat:Sometimes we need not only the latest child node list, but also the latest state information of this node. We can pass an old stat into the API method, and the stat will be replaced by the new stat from the service during the method execution.

Watcher watcher:The watcher is used to monitor the state changes of the znode

DataCallback cb:Asynchronous callback function

Object ctx:Used to pass context information

Synchronous data acquisition

public class Test {
    //The process of creating a session between the client and the server is asynchronous. In other words, the client immediately returns after creating the session through the construction method. At this time, the connection is not fully established
    //After the real session is established, the ZK server will notify the client of an event. After receiving the notification, the client indicates that the connection is being established.
    //Used to wait for ZK server notification
    private static CountDownLatch latch = new CountDownLatch(1);

    private static ZooKeeper zk = null;
    //If there are multiple addresses, separate them with commas
    private static final String connString="127.0.0.1:2181";
    //Time out
    private static final int sessionTimeout = 2000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zk = new ZooKeeper(connString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
                if (Event.KeeperState.SyncConnected == event.getState()) {
                    latch.countDown();
                }
            }
        });
        latch.await();

        //Temporary node: create an interface and return the path l of the node, such as / ZK test
        String path1 = zk.create("/zk-data", "test-data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("created path success : " + path1);


//        byte[] data = zk.getData("/zk-data", true, null);
//        System.out.println("data = " + new String(data));

        * *
        byte[] data = zk.getData("/zk-data", new Watcher() {
            //This is triggered when the / ZK data node information data changes
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
            }
        }, null);
        System.out.println("data = " + new String(data));

        //Close ZK
        zk.close();
    }
}

Modify node data

Interface description

//Synchronization settings
//If version is - 1, it means unconditional update.
//
Stat setData(final String path, byte data[], int version);
//Asynchronous settings
public void setData(final String path, byte data[], int version,
            StatCallback cb, Object ctx);

Parameter interpretation

String path:The path of node

byte data[]:Update data

int version:If version is – 1, it means unconditional update; otherwise, only the given version and the current version of znode will be updated

StatCallback cb:Asynchronous callback function

Object ctx:Passing context information on

Modify data synchronously

public class Test {
    //The process of creating a session between the client and the server is asynchronous. In other words, the client immediately returns after creating the session through the construction method. At this time, the connection is not fully established
    //After the real session is established, the ZK server will notify the client of an event. After receiving the notification, the client indicates that the connection is being established.
    //Used to wait for ZK server notification
    private static CountDownLatch latch = new CountDownLatch(1);

    private static ZooKeeper zk = null;
    //If there are multiple addresses, separate them with commas
    private static final String connString="127.0.0.1:2181";
    //Time out
    private static final int sessionTimeout = 2000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zk = new ZooKeeper(connString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
                if (Event.KeeperState.SyncConnected == event.getState()) {
                    latch.countDown();
                }
            }
        });
        latch.await();

        //Temporary node: create an interface and return the path l of the node, such as / ZK test
        String path1 = zk.create("/zk-data", "test-data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("created path success : " + path1);

        //Access to data
        byte[] data = zk.getData("/zk-data", new Watcher() {
            //This is triggered when the / ZK data node information data changes
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
            }
        }, null);
        System.out.println("data = " + new String(data));

        //Modify data
        zk.setData("/zk-data","test-data-update".getBytes(), -1);
        //Access to data
        byte[] updateData = zk.getData("/zk-data", true, null);
        System.out.println("updateData = " + new String(updateData));

        //Close ZK
        zk.close();
    }
}

Delete node

Interface description

//Synchronous deletion
public void delete(final String path, int version);
//Asynchronous deletion
public void delete(final String path, int version, VoidCallback cb,
            Object ctx)

Parameter interpretation

String path:The path of node

int version:If version is – 1, it means unconditional deletion; otherwise, only the given version and the current version of znode will be deleted

VoidCallbackcb:Asynchronous callback function

Object ctx:Passing context information on

Synchronous deletion of nodes

public class Test {
    //The process of creating a session between the client and the server is asynchronous. In other words, the client immediately returns after creating the session through the construction method. At this time, the connection is not fully established
    //After the real session is established, the ZK server will notify the client of an event. After receiving the notification, the client indicates that the connection is being established.
    //Used to wait for ZK server notification
    private static CountDownLatch latch = new CountDownLatch(1);

    private static ZooKeeper zk = null;
    //If there are multiple addresses, separate them with commas
    private static final String connString="127.0.0.1:2181";
    //Time out
    private static final int sessionTimeout = 2000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zk = new ZooKeeper(connString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
                if (Event.KeeperState.SyncConnected == event.getState()) {
                    latch.countDown();
                }
            }
        });
        latch.await();

        //Creating persistent nodes
        String path1 = zk.create("/zk-data", "test-data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        System.out.println("created path success : " + path1);

        zk.delete("/zk-data",-1);
        //Close ZK
        zk.close();
    }
}

Determine whether the node exists or not

Interface description

public Stat exists(String path, boolean watch);
public Stat exists(final String path, Watcher watcher);

public void exists(String path, boolean watch, StatCallback cb, Object ctx);
public void exists(final String path, Watcher watcher,
            StatCallback cb, Object ctx);

Parameter interpretation

The parameters in this column are similar to the previous analysis

Code practice

public class Test {
    //The process of creating a session between the client and the server is asynchronous. In other words, the client immediately returns after creating the session through the construction method. At this time, the connection is not fully established
    //After the real session is established, the ZK server will notify the client of an event. After receiving the notification, the client indicates that the connection is being established.
    //Used to wait for ZK server notification
    private static CountDownLatch latch = new CountDownLatch(1);

    private static ZooKeeper zk = null;
    //If there are multiple addresses, separate them with commas
    private static final String connString="127.0.0.1:2181";
    //Time out
    private static final int sessionTimeout = 2000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zk = new ZooKeeper(connString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("path = " + event.getPath() + ", eventType = " + event.getType() + ", keeperState = " + event.getState());
                if (Event.KeeperState.SyncConnected == event.getState()) {
                    latch.countDown();
                }
            }
        });
        latch.await();
        //Creating persistent nodes
        String path1 = zk.create("/zk-data", "test-data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        Stat stat1 = zk.exists("/zk-data", true);
        System.out.println(stat1);
        zk.delete("/zk-data",-1);
        Stat stat2 = zk.exists("/zk-data", false);
        System.out.println(stat2);
        //Close ZK
        zk.close();
    }
}

Set listening event API

public byte[] getData(String path, boolean watch, Stat stat);
public byte[] getData(final String path, Watcher watcher, Stat stat);

public Stat exists(String path, boolean watch);
public Stat exists(final String path, Watcher watcher);

boolean watch:If watch is true, the state change of the znode will be sent to the watcher specified by the build zookeeper

Watcher watcher:The watcher is used to monitor the state changes of the znode