ZooKeeper 学习 (五) 开源ZkClient操作ZooKeeper

来源:互联网 发布:西班牙无敌舰队知乎 编辑:程序博客网 时间:2024/05/22 05:16

我们主要从创建会话、创建节点、读取数据、更新数据、删除节点和检查节点是否存在等方面来节点如何使用ZkClient操作ZooKeeper,具体代码如下,鉴于方便,代码写到了一个类里面,虽然不易读,但所有内容都已包括。

package com.tlk.zk.chapter5.zkclient;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.TimeUnit;import org.I0Itec.zkclient.IZkChildListener;import org.I0Itec.zkclient.IZkDataListener;import org.I0Itec.zkclient.ZkClient;import com.alibaba.fastjson.JSON;/** * 开源ZkClient操作ZooKeeper *  * @author tanlk * @date 2017年8月7日 下午11:21:27 */public class ZkClientSample {public static void main(String[] args) throws InterruptedException {ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);Map<String, String> map = new HashMap<String, String>();map.put("1111", "xxxxx");map.put("2222", "ddddd");System.out.println("建立连接");String path = "/zkClient/test/test1";String path2 = "/zkClient/test/test2";String path3 = "/zkClient/test";// 原生API必须父节点存在的情况下才可以创建子节点,zkclient做了封装,如果为true会创建父节点zkClient.createPersistent(path, true);// 更新数据zkClient.writeData(path, map);zkClient.createPersistent(path2, true);System.out.println(path + "节点是否存在:" + zkClient.exists(path));System.out.println(path2 + "节点是否存在:" + zkClient.exists(path2));// 可以通过以下API来获取指定节点的子节点列表List<String> list = zkClient.getChildren(path3);System.out.println(JSON.toJSONString(list));// ZkClient// 没有提供原生API的Watcher注册的功能,不过引入Listener的概念,客户端可以通过注册相关的事件监听来实现对ZooKeeper服务端事件的订阅zkClient.subscribeChildChanges(path, new IZkChildListener() {public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {System.out.println(parentPath + " child changed, currentChilds:" + currentChilds);}});Map<String, String> readData = zkClient.readData(path);System.out.println(path + " read date :" + JSON.toJSONString(readData));// 获取指定节点的数据值,和getChildren类似,readData也引入了ListenerzkClient.subscribeDataChanges(path, new IZkDataListener() {public void handleDataDeleted(String dataPath) throws Exception {System.out.println(dataPath + " 删除");}public void handleDataChange(String dataPath, Object data) throws Exception {System.out.println(dataPath + " 修改了,新的值为:" + JSON.toJSONString(data));}});map.put("33333", "fffff");zkClient.writeData(path, map);zkClient.createPersistent(path + "/hello", true);TimeUnit.SECONDS.sleep(1);// 原生API删除只能删除没有子节点的节点,zkClient也做了封装,可以逐层删除节点zkClient.deleteRecursive(path);TimeUnit.SECONDS.sleep(1);System.out.println(path + "节点是否存在:" + zkClient.exists(path));zkClient.deleteRecursive("/zkClient");// 以逐层删除节点TimeUnit.SECONDS.sleep(1);System.out.println("/zkClient" + "节点是否存在:" + zkClient.exists("/zkClient"));}}


原创粉丝点击