zkClient调用示例

pom.xml文件

            org.apache.zookeeper
            zookeeper
            3.4.10
        
        
            com.101tec
            zkclient
            0.10
        

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 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

你可能感兴趣的:(zkClient调用示例)