我是靠谱客的博主 怕孤单月饼,最近开发中收集的这篇文章主要介绍三种连接ZooKeeper的方式,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1. 使用客户端命令连接Zookeeper
连接Server 
使用命令./zkCli.sh -server 127.0.0.1:2181

连接成功后返回如下信息:

Connecting to 127.0.0.1:2181
2018-06-20 00:13:40,884 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.12-e5259e437540f349646870ea94dc2658c4e44b3b, built on 03/27/2018 03:55 GMT
2018-06-20 00:13:40,887 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=localhost
2018-06-20 00:13:40,887 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_171
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-7.b10.el7.x86_64/jre
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../build/classes:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../build/lib/*.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../lib/slf4j-log4j12-1.7.25.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../lib/slf4j-api-1.7.25.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../lib/netty-3.10.6.Final.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../lib/log4j-1.2.17.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../lib/jline-0.9.94.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../lib/audience-annotations-0.5.0.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../zookeeper-3.4.12.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../src/java/lib/*.jar:/usr/local/services/zookeeper/zookeeper-3.4.12/bin/../conf:
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=/tmp
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Linux
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=3.10.0-862.2.3.el7.x86_64
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=root
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=/root
2018-06-20 00:13:40,889 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=/usr/local/services/zookeeper/zookeeper-3.4.12/bin
2018-06-20 00:13:40,890 [myid:] - INFO  [main:ZooKeeper@441] - Initiating client connection, connectString=127.0.0.1:2181 sessionTimeout=30000 watcher=org.apache.zookeeper.ZooKeeperMain$MyWatcher@446cdf90
Welcome to ZooKeeper!
2018-06-20 00:13:40,928 [myid:] - INFO  [main-SendThread(127.0.0.1:2181):ClientCnxn$SendThread@1028] - Opening socket connection to server 127.0.0.1/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
JLine support is enabled
2018-06-20 00:13:40,989 [myid:] - INFO  [main-SendThread(127.0.0.1:2181):ClientCnxn$SendThread@878] - Socket connection established to 127.0.0.1/127.0.0.1:2181, initiating session
2018-06-20 00:13:41,002 [myid:] - INFO  [main-SendThread(127.0.0.1:2181):ClientCnxn$SendThread@1302] - Session establishment complete on server 127.0.0.1/127.0.0.1:2181, sessionid = 0x100175b98890000, negotiated timeout = 30000

WATCHER::

WatchedEvent state:SyncConnected type:None path:null

输入命令help 显示所有命令

ZooKeeper -server host:port cmd args
    stat path [watch]
    set path data [version]
    ls path [watch]
    delquota [-n|-b] path
    ls2 path [watch]
    setAcl path acl
    setquota -n|-b val path
    history 
    redo cmdno
    printwatches on|off
    delete path [version]
    sync path
    listquota path
    rmr path
    get path [watch]
    create [-s] [-e] path data acl
    addauth scheme auth
    quit 
    getAcl path
    close 
    connect host:port

注意 ls,get,stat 命令有 [watch]参数,可以用来监控节点的变化

命令行工具的一些常用操作命令如下:
connect
切换客户端

connect 127.0.0.1:2182
1
create
使用create命令,可以创建一个Zookeeper节点, 
create [-s] [-e] path data acl 
其中,-s或-e分别指定节点特性,顺序或临时节点,若不指定,则表示持久节点;acl用来进行权限控制。

使用 命令创建zk-test顺序节点

[zk: 127.0.0.1:2181(CONNECTED) 96] create -s /zk-test 0  
Created /zk-test0000000003

使用 create -e /zk-test 123 命令创建zk-test临时节点

[zk: 127.0.0.1:2181(CONNECTED) 96] create -s /zk-test 0  
Created /zk-test0000000003

使用 create /zk-permanent 123 命令创建zk-permanent永久节点

[zk: 127.0.0.1:2182(CONNECTED) 11] create /zk-permanent 123
Created /zk-permanent

//查看所有节点
[zk: 127.0.0.1:2182(CONNECTED) 12] ls /
[test0000000000, zk-permanent, zookeeper, test, zk-test0000000003]

读取节点
ls path [watch] ls命令可以列出Zookeeper指定节点下的所有第一级子节点 
get path [watch] 可以获取Zookeeper指定节点的数据内容和属性信息 
ls2 path [watch] 比ls显示更多信息

命令输出结果如下:

[zk: 127.0.0.1:2182(CONNECTED) 12] ls /
[test0000000000, zk-permanent, zookeeper, test, zk-test0000000003]


[zk: 127.0.0.1:2182(CONNECTED) 13] ls /test
[node4, node5, node2, node3, node8, node6, node7, node1]


[zk: 127.0.0.1:2182(CONNECTED) 14] get /test
123
cZxid = 0x200000010
ctime = Tue Jun 19 20:00:12 PDT 2018
mZxid = 0x200000010
mtime = Tue Jun 19 20:00:12 PDT 2018
pZxid = 0x300000007
cversion = 12
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 3
numChildren = 8


[zk: 127.0.0.1:2182(CONNECTED) 15] ls2 /test
[node4, node5, node2, node3, node8, node6, node7, node1]
cZxid = 0x200000010
ctime = Tue Jun 19 20:00:12 PDT 2018
mZxid = 0x200000010
mtime = Tue Jun 19 20:00:12 PDT 2018
pZxid = 0x300000007
cversion = 12
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 3
numChildren = 8

更新节点
使用set命令,可以更新指定节点的数据内容,用法如下

set path data [version]

使用命令set /test/node1 1更新节点, 每更新一次节点dataVersion 都会变化

[zk: 127.0.0.1:2182(CONNECTED) 17] set /test/node1 1
cZxid = 0x200000011
ctime = Tue Jun 19 20:00:57 PDT 2018
mZxid = 0x30000000f
mtime = Wed Jun 20 01:23:38 PDT 2018
pZxid = 0x200000011
cversion = 0
dataVersion = 6
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 1
numChildren = 0

删除节点
使用delete命令可以删除Zookeeper上的指定节点,用法如下 
delete path [version] 
其中version也是表示数据版本,使用delete /zk-permanent 命令即可删除/zk-permanent节点

2. 使用JAVA连接使用ZK
POM添加引用

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
        </dependency>

使用代码模拟增删改查


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

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class zkClient {
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(1);

        ZooKeeper zk = new ZooKeeper("10.168.x.23:2181,10.168.x.23:2182,10.168.x.23:2183", 3000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    countDownLatch.countDown();
                }
                System.out.println("Watch =>" + event.getType());
            }
        });
        countDownLatch.await();

        System.out.println(zk.getState());
        String node = "/app1";
        Stat state = zk.exists(node, false);
        if (state == null) {
            System.out.println("创建节点");
            String createResult = zk.create(node, "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println(createResult);
        }


        byte[] b = zk.getData(node, false, state);
        System.out.println("获取data值 =》" + new String(b));

        state = zk.setData(node, "1".getBytes(), state.getVersion());
        System.out.println("after update, version changed to =>" + state.getVersion());
        zk.delete(node,state.getVersion());
        System.out.println("delete complete");


        zk.close();
    }
}

3. 使用curator连接使用ZK
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

public class CuratorDemo {

    final static String BasePath = "/curatorTest";

    public static void main(String[] args) throws Exception {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString("10.168.12.23:2181,10.168.12.23:2182,10.168.12.23:2183").sessionTimeoutMs(4000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("curator").build();

        curatorFramework.start();


        Stat stat = curatorFramework.checkExists().forPath(BasePath + "/node1");
        Object o;
        if (stat == null) {

           o=   curatorFramework.create().creatingParentContainersIfNeeded().
                    withMode(CreateMode.PERSISTENT).forPath(BasePath + "/node1", "0".getBytes());
        }


        //存储Stat
        curatorFramework.getData().storingStatIn(stat).forPath(BasePath + "/node1");

        //更新时使用State
        stat = curatorFramework.setData().withVersion(stat.getVersion()).forPath(BasePath + "/node1", "1".getBytes());
        System.out.println("update => " + stat.getVersion());

        curatorFramework.close();
    }
}
--------------------- 
作者:肥龙上天 
来源:CSDN 
原文:https://blog.csdn.net/yangsnow_rain_wind/article/details/80749402 
版权声明:本文为博主原创文章,转载请附上博文链接!

最后

以上就是怕孤单月饼为你收集整理的三种连接ZooKeeper的方式的全部内容,希望文章能够帮你解决三种连接ZooKeeper的方式所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部