您的位置:首页 > 其它

ZooKeeper学习笔记-6---ZkClient使用

2016-11-08 15:21 204 查看
ZkClient是一个开源的ZooKeeper客户端,是在原生的ZooKeeper API接口之上进行包装,是一个更易使用的ZooKeeper客户端。ZkClient在内部实现了Session超时重连、Watcher反复注册等功能,使得ZooKeeper客户端的繁琐细节对开发人员透明。

接下来,我们将从创建会话、创建节点、读取数据、更新数据、删除节点、检测节点等方面介绍ZkClient的使用。

1.会话创建、节点创建、获取子节点、删除节点

public class ZkClientTest {
public static void main(String[] args) throws IOException,InterruptedException {
//创建会话
ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
String path = "/zk-book";

//监测子节点变化
zkClient.subscribeChildChanges(path, new IZkChildListener() {
@Override
public void handleChildChange(String parentPath, List<String> currentChild)
throws Exception {
System.out.println(parentPath + " 's child changed ,currentChilds: " + currentChild);
}
});

//创建节点
zkClient.createPersistent(path);
Thread.sleep(1000);
System.out.println(zkClient.getChildren(path));
Thread.sleep(1000);
zkClient.createPersistent(path + "/c1");
Thread.sleep(1000);
System.out.println(zkClient.getChildren(path));
Thread.sleep(1000);
zkClient.createPersistent(path + "/c2","123");
Thread.sleep(1000);
System.out.println(zkClient.getChildren(path));

//删除节点
Thread.sleep(1000);
zkClient.delete(path + "/c1");
Thread.sleep(1000);
System.out.println(zkClient.getChildren(path));
zkClient.delete(path + "/c2");
System.out.println(zkClient.getChildren(path));
Thread.sleep(1000);
}
}


输出结果:

/zk-book 's child changed ,currentChilds: []
[]
/zk-book 's child changed ,currentChilds: [c1]
[c1]
/zk-book 's child changed ,currentChilds: [c1, c2]
[c1, c2]
/zk-book 's child changed ,currentChilds: [c2]
[c2]
[]
/zk-book 's child changed ,currentChilds: []


2.改变节点数据、检测节点是否存在

public class ZkClientTest {

public static void main(String[] args) throws InterruptedException   {

//创建会话
ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
//创建节点
String path = "/zk-book";
zkClient.createPersistent(path,"123");
//监测节点数据变化
zkClient.subscribeDataChanges(path, new IZkDataListener() {

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

@Override
public void handleDataChange(String dataPath, Object data) throws Exception {
System.out.println("Node " + dataPath + " changed, new data: " +data);
}
});
//读取节点数据
System.out.println(zkClient.readData(path));
zkClient.writeData(path, "456");
Thread.sleep(1000);
System.out.println("Node exists :" + zkClient.exists(path));
zkClient.delete(path);
System.out.println("Node exists :" + zkClient.exists(path));
}
}


输出结果:

123
Node /zk-book changed, new data: 456
Node exists :true
Node exists :false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ZkClient zookeeper