zkClient调用示例

pom.xml文件
<dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.10</version>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>

zkClient的好处1:递归创建,2:递归删除,3:避免不存在异常

递归创建
public class CreateNodeDemo {
    public static void main(String[] args) {
        ZkClient client = new ZkClient("10.143.143.185:6181", 5000);
        String path = "/zk-client/c1";
        // 递归创建节点
        client.createPersistent(path, true);
    }
}
image.png
zkClient注册事件

1:subscribeChildChanges/unsubscribeChildChanges(节点变化)
2:subscribeDataChanges/unsubscribeDataChanges(数据变化)

/**
 * 监听节点变化
 */
public class GetChildrenDemo {
    public static void main(String[] args) throws InterruptedException {
        String path = "/zk-client";
        ZkClient client = new ZkClient("10.143.143.185:6181", 5000);
        client.subscribeChildChanges(path, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                System.out.println(parentPath + "的子节点发生变化: " + currentChilds);
            }
        });

        client.createPersistent(path);
        Thread.sleep(1000);
        System.out.println(client.getChildren(path));
        client.createPersistent(path + "/c1");
        Thread.sleep(1000);
        client.delete(path + "/c1");
        Thread.sleep(1000);
        client.delete(path);
        Thread.sleep(Integer.MAX_VALUE);
    }
}
image.png
/**
 * 监听节点数据变化
 */
public class GetDataDemo {
    public static void main(String[] args) throws InterruptedException {
        String path = "/zk-client";
        ZkClient client = new ZkClient("10.143.143.185:6181", 5000);
        client.createEphemeral(path, "123");

        client.subscribeDataChanges(path, new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println(dataPath + " changed: " + data);
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println(dataPath + " deleted");
            }
        });

        System.out.println(client.readData(path).toString());
        client.writeData(path, "456");
        Thread.sleep(1000);
        client.delete(path);
        Thread.sleep(Integer.MAX_VALUE);
    }
}
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容