zk客户端: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);
    }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值