代码
1 /**
2 * 创建zk客户端
3 * 实现循环监听的两个必要条件:1.程序不能结束2.递归调用监听器
4 * @author tele
5 *
6 */
7 public class Demo {
8 private int sessionTimeout = 2000;
9 //多个节点用逗号隔开
10 private String connectString="hadoop002:2181,hadoop003:2181";
11 private ZooKeeper zkClient;
12
13 /**
14 * 初始化
15 * @throws IOException
16 */
17 @Before
18 public void init() throws IOException {
19 zkClient = new ZooKeeper(connectString, sessionTimeout,new Watcher(){
20 @Override
21 public void process(WatchedEvent event) {
22 try {
23 //实现循环监听
24 List<String> list = zkClient.getChildren("/",true);
25 } catch (KeeperException e) {
26 e.printStackTrace();
27 } catch (InterruptedException e) {
28 e.printStackTrace();
29 }
30 System.out.println(event.getType() + " " + "path:" + event.getPath());
31
32 }
33 });
34 }
35
36
37 /**
38 * 创建节点
39 * @throws InterruptedException
40 * @throws KeeperException
41 */
42 @Test
43 public void createNode() throws KeeperException, InterruptedException {
44 String nodeName = zkClient.create("/wycrencaiss","ok".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT_SEQUENTIAL);
45 System.out.println("创建的节点名称是-----" + nodeName);
46 }
47
48
49
50 /**
51 * 获取节点
52 * @throws InterruptedException
53 * @throws KeeperException
54 */
55 @Test
56 public void getNode() throws KeeperException, InterruptedException {
57 List<String> list = zkClient.getChildren("/",true);
58 for (String string : list) {
59 System.out.println(string);
60 }
61
62 Thread.sleep(Long.MAX_VALUE);
63 }
64
65
66 /**
67 * 判断节点是否存在
68 * @throws InterruptedException
69 * @throws KeeperException
70 */
71 @Test
72 public void isExist() throws KeeperException, InterruptedException {
73
74 Stat stat = zkClient.exists("/wyc",true);
75 System.out.println(stat==null?"not exist":"exist");
76 Thread.sleep(Long.MAX_VALUE);
77 }
78 }
maven
1 <dependency>
2 <groupId>org.apache.zookeeper</groupId>
3 <artifactId>zookeeper</artifactId>
4 <version>3.4.10</version>
5 </dependency>
6 <dependency>
7 <groupId>junit</groupId>
8 <artifactId>junit</artifactId>
9 <version>4.11</version>
10 <scope>test</scope>
11 </dependency>