1 package com.karat.cn.zookeeper.zkclient;
2
3 import java.util.List;
4 import java.util.concurrent.TimeUnit;
5
6 import org.I0Itec.zkclient.IZkChildListener;
7 import org.I0Itec.zkclient.IZkDataListener;
8 import org.I0Itec.zkclient.ZkClient;
9 /**
10 * 节点操作
11 * @author Administrator
12 *
13 */
14 public class ZkClientApiOperatorDemo {
15
16 private final static String CONNECTSTRING="47.107.121.215:2181";
17
18 private static ZkClient getInstance(){
19 return new ZkClient(CONNECTSTRING,10000);//10000是连接超时时间
20 }
21
22 public static void main(String[] args) throws InterruptedException {
23 ZkClient zkClient=getInstance();//连接
24 //zkClient.createEphemeral("/zkClient");//创建临时节点
25 //zkClient中提供递归创建父节点的功能
26 //zkClient.createPersistent("/zkClient/a/b/c/d",true);//创建持久化节点
27 //删除节点
28 //zkClient.delete("/zkClient");
29 //递归删除节点
30 //zkClient.deleteRecursive("/zkClient");
31 //获取子节点
32 List<String> list=zkClient.getChildren("/zkClient/a");
33 System.out.println(list);
34
35
36 //watcher(订阅获取)
37 zkClient.subscribeDataChanges("/node", new IZkDataListener() {
38
39 @Override
40 public void handleDataDeleted(String dataPath) throws Exception {
41 // TODO Auto-generated method stub
42
43 }
44
45 @Override
46 public void handleDataChange(String dataPath, Object data) throws Exception {
47 // TODO Auto-generated method stub
48 System.out.println("节点名称:"+dataPath+"->节点修改后的值"+data);
49 }
50 });
51
52 zkClient.writeData("/node", "123");//修改节点的数据
53 TimeUnit.SECONDS.sleep(2);//上述事件是异步的,需要睡两秒
54
55 zkClient.subscribeChildChanges("/node", new IZkChildListener() {
56
57 @Override
58 public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
59 // TODO Auto-generated method stub
60
61 }
62 });
63 }
64 }