zkClient api使用

maven添加依赖:

        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>

 

代码1 创建查看节点:

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;

public class ZkClientApiTest {

    private static final String CLUSTER = "192.168.53.180:2181";
    
    public static void main(String[] args) {
        // 连接集群
        ZkClient zkClient = new ZkClient(CLUSTER);

        // 创建节点
        String nodeName = zkClient.create("/age","666", CreateMode.PERSISTENT);
        System.out.println(nodeName);

        // 读取节点数据
        Object data = zkClient.readData("/age");
        System.out.println(data);
    }
}

控制台打印结果:

 客户端查看结果:

 

代码2 删除节点:

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;

public class ZkClientApiTest {

    private static final String CLUSTER = "192.168.53.180:2181";

    public static void main(String[] args) {
        // 连接集群
        ZkClient zkClient = new ZkClient(CLUSTER);

        // 查看节点是否存在
        System.out.println(zkClient.exists("/age"));

        // 删除节点
        zkClient.delete("/age");
        System.out.println(zkClient.exists("/age"));
    }
}

 客户端查看到已经删除/age

posted @ 2021-02-03 11:13  圣金巫灵  阅读(95)  评论(0编辑  收藏  举报