fdsfdfe 发表于 2015-8-14 08:48:34

客户端操作zookeeper服务代码示例

本文主要贴出通过zookeeper的客户端类访问zookeeper的示例,以及其它第三方更高层次的封装的客户端使用。
1.通过org.apache.zookeeper.ZooKeeper来操作zookeeper服务
有关zookeeper服务的部署参见文:http://www.iyunv.com/thread-98262-1-1.html 下文将有代码示例展示通过编码方式在应用中启动zookeeper服务。

ZooKeeper类对zookeeper服务的简单操作示例代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package secondriver.dubbo.client;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* Author : secondriver
*/
public class TestZookeeper {

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

      //创建zookeeper客户端
      ZooKeeper zooKeeper = new ZooKeeper("192.168.88.153:2181", 1000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("EventType:" + event.getType().name());
            }
      });

      //获取"/" node下的所有子node
      List<String> znodes = zooKeeper.getChildren("/", true);
      for (String path : znodes) {
            System.out.println(path);
      }

      //创建开放权限的持久化node "/test"
      String rs = zooKeeper.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode
                .PERSISTENT);
      System.out.println(rs);

      //同步获取"/test" node的数据
      Stat stat = new Stat();
      byte[] data = zooKeeper.getData("/test", true, stat);
      System.out.println("value=" + new String(data));
      System.out.println(stat.toString());


      //异步获取"/test" node的数据
      zooKeeper.getData("/test", true, new AsyncCallback.DataCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                System.out.println(rc);
                System.out.println(path);
                System.out.println(ctx);
                System.out.printf(new String(data));
                System.out.println(stat.toString());

            }
      }, "Object ctx ..(提供的外部对象)");

      TimeUnit.SECONDS.sleep(10);

      zooKeeper.close();
    }
}





上述代码依赖zookeeper包


1
2
3
4
5
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.6</version>
</dependency>





2.通过zkclient操作zookeeper服务
zkclient github: https://github.com/sgroschupf/zkclient
后续有二次开发的版本:
项目: https://github.com/adyliu/zkclient
文档: https://github.com/adyliu/zkclient/wiki/tutorial

下文代码示例使用sgroschupf/zkclient,依赖Zookeeper包。
mavensgroschupf/zkclient


1
2
3
4
5
<dependency>
    <groupId>com.101tec</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.5</version>
</dependency>





应用内server+client:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package secondriver.dubbo.server;

import org.I0Itec.zkclient.IDefaultNameSpace;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkServer;
import org.apache.zookeeper.CreateMode;

import java.io.IOException;
/**
* Author : secondriver
*/
public class TestI0ItecZk {

    public static void main(String[] args) throws IOException {
      //Server + Client
      ZkServer zkServer = new ZkServer("D:/data", "D:/log", new IDefaultNameSpace() {
            @Override
            public void createDefaultNameSpace(ZkClient zkClient) {
                zkClient.create("/default", "defalut-name-space", CreateMode.PERSISTENT);
            }
      });

      zkServer.start();

      ZkClient zkClient = zkServer.getZkClient();

      boolean exists = zkClient.exists("/default");
      if (exists) {
            System.out.println("default name space init create succeed.");
      } else {
            System.out.println("default name space init create failed.");
      }

      System.in.read();

      zkClient.close();
      zkServer.shutdown();
    }
}





应用外部署server,使用client访问:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package secondriver.dubbo.server;

import org.I0Itec.zkclient.ZkClient;

import java.util.List;

/**
* Author : secondriver
*/
public class TestZkClient {

    public static void main(String[] args) {
      //Only use client
      ZkClient zkc = new ZkClient("192.168.88.153:2181,192.168.88.153:2182,192.168.88.153:2183");
      List<String> childrens = zkc.getChildren("/");
      for (String child : childrens) {
            System.out.println(child);
      }
    }
}





下文代码示例使用adyliu/zkclient,同样依赖Zookeeper包,启动Zookeeper服务并做操作。

maven adyliu/zkclient:


1
2
3
4
5
<dependency>
    <groupId>com.github.adyliu</groupId>
    <artifactId>zkclient</artifactId>
    <version>2.1.1</version>
</dependency>






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package secondriver.dubbo.server;

import com.github.zkclient.*;

import java.io.IOException;
import java.util.List;

/**
* Author : secondriver
*/
public class TestZk {


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

      String home = System.getProperty("user.home");

      //创建zookeeper服务并启动
      ZkServer zkServer = new ZkServer(home + "/zookeeper/data", home + "/zookeeper/log", 2181);
      zkServer.start();

      //方式一
//      ZkClient zkClient = new ZkClient("127.0.0.1:2181", 1000);
      //方式二
      ZkClient zkClient = zkServer.getZkClient();

      String path = "/test" + Math.random();

      //数据监听
      final IZkDataListener dataListener = new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, byte[] data) throws Exception {
                System.out.println(dataPath + " data change");
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {

            }
      };

      //结点(node)监听
      final IZkChildListener childListener = new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception {
                System.out.println(parentPath + " parentPath");
                for (String path : currentChildren) {
                  System.out.println(path);
                }
            }
      };

      //为指定node添加监听
      zkClient.subscribeDataChanges(path, dataListener);
      zkClient.subscribeChildChanges("/", childListener);

      //zkclient操作Zookeeper服务
      ///检测node是否存在
      if (zkClient.exists("/zookeeper")) {
            System.out.println("Exist zookeeper path");
      } else {
            System.out.println("Not Exist zookeeper path");
      }

      zkClient.createPersistent(path, path.getBytes());
      byte[] before = zkClient.readData(path);
      System.out.println("before:" + new String(before));

      //以原子的方式更新指定的path node的数据
      zkClient.cas(path, new IZkClient.DataUpdater() {

            @Override
            public byte[] update(byte[] currentData) {
                return new String(currentData).concat(new String(" updated")).getBytes();
            }
      });

      byte[] after = zkClient.readData(path);
      System.out.println("after:" + new String(after));

      //取消指定path node的数据监听
      zkClient.unsubscribeDataChanges(path, dataListener);

      zkClient.writeData(path, "new-data".getBytes());

      byte[] dataBytes = zkClient.readData(path);
      String data = new String(dataBytes);
      System.out.println(path + " data :" + data);

      System.in.read();

      zkClient.close();
      zkServer.shutdown();
    }
}





3. Zookeeper客户端和富Zookeeper框架之curator

github: https://github.com/Netflix/curator
已成为apache项目:http://curator.apache.org

页: [1]
查看完整版本: 客户端操作zookeeper服务代码示例