设为首页 收藏本站
查看: 2765|回复: 0

[经验分享] 客户端操作zookeeper服务代码示例

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-8-14 08:48:34 | 显示全部楼层 |阅读模式
本文主要贴出通过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包。
  maven  sgroschupf/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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-98742-1-1.html 上篇帖子: 单台机器部署zookeeper集群 下篇帖子: 使用ZooKeeper ACL特性进行znode控制 第三方 客户端
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表