zookeeper-分布式协调工具(一),java操作zookeeper

什么是zookeeper

 1.Zookeeper是一个分布式开源框架,提供了协调分布式应用的基本服务,它向外部应用暴露一组通用服务——分布式同步、命名服务、集群维护等,简化分布式应用协调及其管理的难度,提供高性能的分布式服务。ZooKeeper本身可以以单机模式安装运行,不过它的长处在于通过分布式ZooKeeper集群,基于一定的策略来保证ZooKeeper集群的稳定性和可用性,从而实现分布式应用的可靠性。

 

zookeeper运用场景

1.dubbo+zk实现rpc远程调用中,zk在其中的作用类似springcloud中的eureka注册服务中心,管理接口服务

2.发布订阅

3.负载均衡

4.分布通知

5.分布式锁

 

zokeeper存储数据结构(类似xml数据结构)

在zk的节点中,每个节点名称是不可以重复的(实现分布式锁的关键性),可以依次无限递增。节点的类型可以分为四种:

1.持久节点,一旦创建就保存到硬盘上面

2.临时节点,创建以后如果断开连接则该节点自动删除

3.顺序持久节点

4.顺序临时节点

每个节点都可以通过节点事件监听,对于节点的变化(增,删,改)都能获取到

例如:在使用zk作为dobbo注册服务中心的时候

在Windows环境下安装运行zk

1. 下载Windows版本zk,解压以后,修改配置文件zoo_sample.cfg名字为zoo.cfg

2.在zk的bi目录下找到zkServer.bat 启动zk

3.在zk的bi目录下找到zkCli 启动zk的客户端工具,可以在cmd里面对zk的节点进行创建 修改和删除,可以根据zk的可视化管理工具进行查看,例如创建一个会员服务 ip地址是 127.0.0.1

 

可以通过ls 空格 / 查看当前的节点

 

 

JAVA如何操作Zookeeper

 1.导入zookeeper所需要的依赖:

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

 

  2.编写java类创建zookeeper的节点

package com.zk.demo;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class CreateZookeeper {
    /**
     * ZK地址和端口
     */
    private static final String CONNETTION_ADDR = "127.0.0.1:2181";
    /**
     * session超时时间
     */
    private static final int SESSION_TIMEOUT = 5000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zk = new ZooKeeper(CONNETTION_ADDR, SESSION_TIMEOUT, new Watcher() {
            public void process(WatchedEvent event) {
                // 获取时间的状态
                KeeperState keeperState = event.getState();
                EventType tventType = event.getType();
                // 如果是建立连接
                if (KeeperState.SyncConnected == keeperState) {
                    if (EventType.None == tventType) {
                        System.out.println("创建zk连接");
                    }
                }
            }
        });
        zk.create("/zk", "testZookeeper".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("创建节点成功");
        zk.close();
    }
}

 

3.运行测试类,启动zk服务,通过命令或者可视化客户端查看生成的zk节点

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/E:/developer/mvnResponsity/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/E:/developer/mvnResponsity/org/slf4j/slf4j-log4j12/1.7.26/slf4j-log4j12-1.7.26.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
15:37:24.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:zookeeper.version=3.4.14-4c25d480e66aadd371de8bd2fd8da255ac140bcf, built on 03/06/2019 16:18 GMT
15:37:24.268 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:host.name=NNH1J2ASSQP10BA
15:37:24.268 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.version=1.8.0_172
15:37:24.268 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.vendor=Oracle Corporation
15:37:24.268 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.home=E:\Java\jdk1.8.0_172\jre
15:37:24.268 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.class.path=E:\Java\jdk1.8.0_172\jre\lib\resources.jar;E:\Java\jdk1.8.0_172\jre\lib\rt.jar;E:\Java\jdk1.8.0_172\jre\lib\jsse.jar;E:\Java\jdk1.8.0_172\jre\lib\jce.jar;E:\Java\jdk1.8.0_172\jre\lib\charsets.jar;E:\Java\jdk1.8.0_172\jre\lib\jfr.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\access-bridge-64.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\cldrdata.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\dnsns.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\jaccess.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\jfxrt.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\localedata.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\nashorn.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunec.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunjce_provider.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunmscapi.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunpkcs11.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\zipfs.jar;E:\code\servlet\java-zk\target\classes;E:\code\servlet\java-zk\lib\zookeeper-3.4.14.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-starter\1.5.21.RELEASE\spring-boot-starter-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot\1.5.21.RELEASE\spring-boot-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-context\4.3.24.RELEASE\spring-context-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-aop\4.3.24.RELEASE\spring-aop-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-beans\4.3.24.RELEASE\spring-beans-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-expression\4.3.24.RELEASE\spring-expression-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-autoconfigure\1.5.21.RELEASE\spring-boot-autoconfigure-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-starter-logging\1.5.21.RELEASE\spring-boot-starter-logging-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\ch\qos\logback\logback-classic\1.1.11\logback-classic-1.1.11.jar;E:\developer\mvnResponsity\ch\qos\logback\logback-core\1.1.11\logback-core-1.1.11.jar;E:\developer\mvnResponsity\org\slf4j\jcl-over-slf4j\1.7.26\jcl-over-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\log4j-over-slf4j\1.7.26\log4j-over-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\springframework\spring-core\4.3.24.RELEASE\spring-core-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;E:\developer\mvnResponsity\org\apache\zookeeper\zookeeper\3.4.14\zookeeper-3.4.14.jar;E:\developer\mvnResponsity\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\slf4j-log4j12\1.7.26\slf4j-log4j12-1.7.26.jar;E:\developer\mvnResponsity\com\github\spotbugs\spotbugs-annotations\3.1.9\spotbugs-annotations-3.1.9.jar;E:\developer\mvnResponsity\com\google\code\findbugs\jsr305\3.0.2\jsr305-3.0.2.jar;E:\developer\mvnResponsity\log4j\log4j\1.2.17\log4j-1.2.17.jar;E:\developer\mvnResponsity\jline\jline\0.9.94\jline-0.9.94.jar;E:\developer\mvnResponsity\org\apache\yetus\audience-annotations\0.5.0\audience-annotations-0.5.0.jar;E:\developer\mvnResponsity\io\netty\netty\3.10.6.Final\netty-3.10.6.Final.jar
15:37:24.268 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.library.path=E:\Java\jdk1.8.0_172\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;E:/Java/jdk1.8.0_172/jre/bin/server;E:/Java/jdk1.8.0_172/jre/bin;E:/Java/jdk1.8.0_172/jre/lib/amd64;E:\xftp\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\Java\jdk1.8.0_172\lib;E:\Java\jdk1.8.0_172\jre\bin;E:\maven\apache-maven-3.5.3\bin;E:\software\mysql\mysql-8.0.15-winx64;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;;E:\sts\spring-tool-suite-3.9.4.RELEASE-e4.7.3a-win32-x86_64\sts-bundle\sts-3.9.4.RELEASE;;.
15:37:24.269 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.io.tmpdir=C:\Users\ADMINI~1\AppData\Local\Temp\
15:37:24.269 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.compiler=<NA>
15:37:24.269 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.name=Windows 10
15:37:24.269 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.arch=amd64
15:37:24.269 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.version=10.0
15:37:24.269 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.name=Administrator
15:37:24.269 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.home=C:\Users\Administrator
15:37:24.269 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.dir=E:\code\servlet\java-zk
15:37:24.270 [main] INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=127.0.0.1:2181 sessionTimeout=5000 watcher=com.zk.demo.CreateZookeeper$1@6d21714c
15:37:24.272 [main] DEBUG org.apache.zookeeper.ClientCnxn - zookeeper.disableAutoWatchReset is false
15:37:24.393 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.SaslServerPrincipal - Canonicalized address to 127.0.0.1
15:37:24.395 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Opening socket connection to server 127.0.0.1/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
15:37:24.396 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Socket connection established to 127.0.0.1/127.0.0.1:2181, initiating session
15:37:24.397 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Session establishment request sent on 127.0.0.1/127.0.0.1:2181
15:37:24.401 [main-SendThread(127.0.0.1:2181)] WARN org.apache.zookeeper.ClientCnxnSocket - Connected to an old server; r-o mode will be unavailable
15:37:24.401 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Session establishment complete on server 127.0.0.1/127.0.0.1:2181, sessionid = 0x16b07ab1dee0002, negotiated timeout = 5000
创建zk连接
15:37:24.407 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x16b07ab1dee0002, packet:: clientPath:null serverPath:null finished:false header:: 1,1  replyHeader:: 1,62,0  request:: '/zk,#746573745a6f6f6b6565706572,v{s{31,s{'world,'anyone}}},0  response:: '/zk 
创建节点成功
15:37:24.407 [main] DEBUG org.apache.zookeeper.ZooKeeper - Closing session: 0x16b07ab1dee0002
15:37:24.407 [main] DEBUG org.apache.zookeeper.ClientCnxn - Closing client for session: 0x16b07ab1dee0002
15:37:24.410 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x16b07ab1dee0002, packet:: clientPath:null serverPath:null finished:false header:: 2,-11  replyHeader:: 2,63,0  request:: null response:: null
15:37:24.410 [main] DEBUG org.apache.zookeeper.ClientCnxn - Disconnecting client for session: 0x16b07ab1dee0002
15:37:24.410 [main] INFO org.apache.zookeeper.ZooKeeper - Session: 0x16b07ab1dee0002 closed
15:37:24.411 [main-EventThread] INFO org.apache.zookeeper.ClientCnxn - EventThread shut down for session: 0x16b07ab1dee0002

 

 4.在上述代码中可能会出现一个问题 就是zk创建连接的时候 是一个异步操作,可以通过测试得知:

package com.zk.demo;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class CreateZookeeper {
    /**
     * ZK地址和端口
     */
    private static final String CONNETTION_ADDR = "127.0.0.1:2181";
    /**
     * session超时时间
     */
    private static final int SESSION_TIMEOUT = 5000;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zk = new ZooKeeper(CONNETTION_ADDR, SESSION_TIMEOUT, new Watcher() {
            public void process(WatchedEvent event) {
                try {
                    //休眠6秒
                    Thread.sleep(6000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 获取时间的状态
                KeeperState keeperState = event.getState();
                EventType tventType = event.getType();
                // 如果是建立连接
                if (KeeperState.SyncConnected == keeperState) {
                    if (EventType.None == tventType) {
                        System.out.println("创建zk连接");
                    }
                }
            }
        });
        zk.create("/zksyn", "testZookeeper".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("创建节点成功");
        zk.close();
    }
}

运行结果:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/E:/developer/mvnResponsity/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/E:/developer/mvnResponsity/org/slf4j/slf4j-log4j12/1.7.26/slf4j-log4j12-1.7.26.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
15:49:00.264 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:zookeeper.version=3.4.14-4c25d480e66aadd371de8bd2fd8da255ac140bcf, built on 03/06/2019 16:18 GMT
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:host.name=NNH1J2ASSQP10BA
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.version=1.8.0_172
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.vendor=Oracle Corporation
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.home=E:\Java\jdk1.8.0_172\jre
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.class.path=E:\Java\jdk1.8.0_172\jre\lib\resources.jar;E:\Java\jdk1.8.0_172\jre\lib\rt.jar;E:\Java\jdk1.8.0_172\jre\lib\jsse.jar;E:\Java\jdk1.8.0_172\jre\lib\jce.jar;E:\Java\jdk1.8.0_172\jre\lib\charsets.jar;E:\Java\jdk1.8.0_172\jre\lib\jfr.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\access-bridge-64.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\cldrdata.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\dnsns.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\jaccess.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\jfxrt.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\localedata.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\nashorn.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunec.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunjce_provider.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunmscapi.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunpkcs11.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\zipfs.jar;E:\code\servlet\java-zk\target\classes;E:\code\servlet\java-zk\lib\zookeeper-3.4.14.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-starter\1.5.21.RELEASE\spring-boot-starter-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot\1.5.21.RELEASE\spring-boot-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-context\4.3.24.RELEASE\spring-context-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-aop\4.3.24.RELEASE\spring-aop-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-beans\4.3.24.RELEASE\spring-beans-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-expression\4.3.24.RELEASE\spring-expression-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-autoconfigure\1.5.21.RELEASE\spring-boot-autoconfigure-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-starter-logging\1.5.21.RELEASE\spring-boot-starter-logging-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\ch\qos\logback\logback-classic\1.1.11\logback-classic-1.1.11.jar;E:\developer\mvnResponsity\ch\qos\logback\logback-core\1.1.11\logback-core-1.1.11.jar;E:\developer\mvnResponsity\org\slf4j\jcl-over-slf4j\1.7.26\jcl-over-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\log4j-over-slf4j\1.7.26\log4j-over-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\springframework\spring-core\4.3.24.RELEASE\spring-core-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;E:\developer\mvnResponsity\org\apache\zookeeper\zookeeper\3.4.14\zookeeper-3.4.14.jar;E:\developer\mvnResponsity\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\slf4j-log4j12\1.7.26\slf4j-log4j12-1.7.26.jar;E:\developer\mvnResponsity\com\github\spotbugs\spotbugs-annotations\3.1.9\spotbugs-annotations-3.1.9.jar;E:\developer\mvnResponsity\com\google\code\findbugs\jsr305\3.0.2\jsr305-3.0.2.jar;E:\developer\mvnResponsity\log4j\log4j\1.2.17\log4j-1.2.17.jar;E:\developer\mvnResponsity\jline\jline\0.9.94\jline-0.9.94.jar;E:\developer\mvnResponsity\org\apache\yetus\audience-annotations\0.5.0\audience-annotations-0.5.0.jar;E:\developer\mvnResponsity\io\netty\netty\3.10.6.Final\netty-3.10.6.Final.jar
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.library.path=E:\Java\jdk1.8.0_172\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;E:/Java/jdk1.8.0_172/jre/bin/server;E:/Java/jdk1.8.0_172/jre/bin;E:/Java/jdk1.8.0_172/jre/lib/amd64;E:\xftp\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\Java\jdk1.8.0_172\lib;E:\Java\jdk1.8.0_172\jre\bin;E:\maven\apache-maven-3.5.3\bin;E:\software\mysql\mysql-8.0.15-winx64;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;;E:\sts\spring-tool-suite-3.9.4.RELEASE-e4.7.3a-win32-x86_64\sts-bundle\sts-3.9.4.RELEASE;;.
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.io.tmpdir=C:\Users\ADMINI~1\AppData\Local\Temp\
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.compiler=<NA>
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.name=Windows 10
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.arch=amd64
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.version=10.0
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.name=Administrator
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.home=C:\Users\Administrator
15:49:00.266 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.dir=E:\code\servlet\java-zk
15:49:00.267 [main] INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=127.0.0.1:2181 sessionTimeout=5000 watcher=com.zk.demo.CreateZookeeper$1@6d21714c
15:49:00.269 [main] DEBUG org.apache.zookeeper.ClientCnxn - zookeeper.disableAutoWatchReset is false
15:49:00.381 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.SaslServerPrincipal - Canonicalized address to 127.0.0.1
15:49:00.383 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Opening socket connection to server 127.0.0.1/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
15:49:00.384 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Socket connection established to 127.0.0.1/127.0.0.1:2181, initiating session
15:49:00.385 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Session establishment request sent on 127.0.0.1/127.0.0.1:2181
15:49:00.399 [main-SendThread(127.0.0.1:2181)] WARN org.apache.zookeeper.ClientCnxnSocket - Connected to an old server; r-o mode will be unavailable
15:49:00.399 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Session establishment complete on server 127.0.0.1/127.0.0.1:2181, sessionid = 0x16b07ab1dee0005, negotiated timeout = 5000
15:49:00.403 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x16b07ab1dee0005, packet:: clientPath:null serverPath:null finished:false header:: 1,1  replyHeader:: 1,71,0  request:: '/zksyn,#746573745a6f6f6b6565706572,v{s{31,s{'world,'anyone}}},0  response:: '/zksyn 
创建节点成功
15:49:00.404 [main] DEBUG org.apache.zookeeper.ZooKeeper - Closing session: 0x16b07ab1dee0005
15:49:00.404 [main] DEBUG org.apache.zookeeper.ClientCnxn - Closing client for session: 0x16b07ab1dee0005
15:49:00.406 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x16b07ab1dee0005, packet:: clientPath:null serverPath:null finished:false header:: 2,-11  replyHeader:: 2,72,0  request:: null response:: null
15:49:00.406 [main] DEBUG org.apache.zookeeper.ClientCnxn - Disconnecting client for session: 0x16b07ab1dee0005
15:49:00.406 [main] INFO org.apache.zookeeper.ZooKeeper - Session: 0x16b07ab1dee0005 closed

 

从运行的结果可以看出,zk的创建是个异步过程,创建任务是新开了一条线程,从最后的打印日志也知道,新开的线程还是一条守护线程(主线程运行死亡,则自身死亡),所以 在zk的创建可能会出现 zk的连接还没有创建成功,就已经开始创建节点,所以 这里最好要阻塞,保证 zk创建连接成功以后,才能创建zk节点,可以通过线程join来确定线程先后执行顺序,也可以使用信号量CountDownLatch,每次执行类似i--操作,当值为0的时候 则不阻塞,其余状态阻塞。修改以后的代码:

package com.zk.demo;

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

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class CreateZookeeper {
    /**
     * ZK地址和端口
     */
    private static final String CONNETTION_ADDR = "127.0.0.1:2181";
    /**
     * session超时时间
     */
    private static final int SESSION_TIMEOUT = 5000;
    /**
     * 用于在zk创建连接的时候阻塞,不让主程序往下运行 1表示初始值,每次调用则-1 等于0的时候 取消阻塞
     */
    private static final CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zk = new ZooKeeper(CONNETTION_ADDR, SESSION_TIMEOUT, new Watcher() {
            public void process(WatchedEvent event) {
                try {
                    // 休眠6秒
                    Thread.sleep(6000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 获取时间的状态
                KeeperState keeperState = event.getState();
                EventType tventType = event.getType();
                // 如果是建立连接
                if (KeeperState.SyncConnected == keeperState) {
                    if (EventType.None == tventType) {
                        System.out.println("等待6秒以后");
                        // 调用一次-1
                        countDownLatch.countDown();
                    }
                }
            }
        });
        // 进行阻塞,等待,只有值为0的时候 才放行
        countDownLatch.await();
        String create = zk.create("/zksyn3", "testZookeeper".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("创建节点成功" + create);
        zk.close();
    }
}

 

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/E:/developer/mvnResponsity/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/E:/developer/mvnResponsity/org/slf4j/slf4j-log4j12/1.7.26/slf4j-log4j12-1.7.26.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
16:01:38.559 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:zookeeper.version=3.4.14-4c25d480e66aadd371de8bd2fd8da255ac140bcf, built on 03/06/2019 16:18 GMT
16:01:38.560 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:host.name=NNH1J2ASSQP10BA
16:01:38.560 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.version=1.8.0_172
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.vendor=Oracle Corporation
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.home=E:\Java\jdk1.8.0_172\jre
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.class.path=E:\Java\jdk1.8.0_172\jre\lib\resources.jar;E:\Java\jdk1.8.0_172\jre\lib\rt.jar;E:\Java\jdk1.8.0_172\jre\lib\jsse.jar;E:\Java\jdk1.8.0_172\jre\lib\jce.jar;E:\Java\jdk1.8.0_172\jre\lib\charsets.jar;E:\Java\jdk1.8.0_172\jre\lib\jfr.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\access-bridge-64.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\cldrdata.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\dnsns.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\jaccess.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\jfxrt.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\localedata.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\nashorn.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunec.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunjce_provider.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunmscapi.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\sunpkcs11.jar;E:\Java\jdk1.8.0_172\jre\lib\ext\zipfs.jar;E:\code\servlet\java-zk\target\classes;E:\code\servlet\java-zk\lib\zookeeper-3.4.14.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-starter\1.5.21.RELEASE\spring-boot-starter-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot\1.5.21.RELEASE\spring-boot-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-context\4.3.24.RELEASE\spring-context-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-aop\4.3.24.RELEASE\spring-aop-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-beans\4.3.24.RELEASE\spring-beans-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\spring-expression\4.3.24.RELEASE\spring-expression-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-autoconfigure\1.5.21.RELEASE\spring-boot-autoconfigure-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\org\springframework\boot\spring-boot-starter-logging\1.5.21.RELEASE\spring-boot-starter-logging-1.5.21.RELEASE.jar;E:\developer\mvnResponsity\ch\qos\logback\logback-classic\1.1.11\logback-classic-1.1.11.jar;E:\developer\mvnResponsity\ch\qos\logback\logback-core\1.1.11\logback-core-1.1.11.jar;E:\developer\mvnResponsity\org\slf4j\jcl-over-slf4j\1.7.26\jcl-over-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\log4j-over-slf4j\1.7.26\log4j-over-slf4j-1.7.26.jar;E:\developer\mvnResponsity\org\springframework\spring-core\4.3.24.RELEASE\spring-core-4.3.24.RELEASE.jar;E:\developer\mvnResponsity\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;E:\developer\mvnResponsity\org\apache\zookeeper\zookeeper\3.4.14\zookeeper-3.4.14.jar;E:\developer\mvnResponsity\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;E:\developer\mvnResponsity\org\slf4j\slf4j-log4j12\1.7.26\slf4j-log4j12-1.7.26.jar;E:\developer\mvnResponsity\com\github\spotbugs\spotbugs-annotations\3.1.9\spotbugs-annotations-3.1.9.jar;E:\developer\mvnResponsity\com\google\code\findbugs\jsr305\3.0.2\jsr305-3.0.2.jar;E:\developer\mvnResponsity\log4j\log4j\1.2.17\log4j-1.2.17.jar;E:\developer\mvnResponsity\jline\jline\0.9.94\jline-0.9.94.jar;E:\developer\mvnResponsity\org\apache\yetus\audience-annotations\0.5.0\audience-annotations-0.5.0.jar;E:\developer\mvnResponsity\io\netty\netty\3.10.6.Final\netty-3.10.6.Final.jar
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.library.path=E:\Java\jdk1.8.0_172\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;E:/Java/jdk1.8.0_172/jre/bin/server;E:/Java/jdk1.8.0_172/jre/bin;E:/Java/jdk1.8.0_172/jre/lib/amd64;E:\xftp\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\Java\jdk1.8.0_172\lib;E:\Java\jdk1.8.0_172\jre\bin;E:\maven\apache-maven-3.5.3\bin;E:\software\mysql\mysql-8.0.15-winx64;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;;E:\sts\spring-tool-suite-3.9.4.RELEASE-e4.7.3a-win32-x86_64\sts-bundle\sts-3.9.4.RELEASE;;.
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.io.tmpdir=C:\Users\ADMINI~1\AppData\Local\Temp\
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.compiler=<NA>
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.name=Windows 10
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.arch=amd64
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.version=10.0
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.name=Administrator
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.home=C:\Users\Administrator
16:01:38.561 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.dir=E:\code\servlet\java-zk
16:01:38.562 [main] INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=127.0.0.1:2181 sessionTimeout=5000 watcher=com.zk.demo.CreateZookeeper$1@6d21714c
16:01:38.564 [main] DEBUG org.apache.zookeeper.ClientCnxn - zookeeper.disableAutoWatchReset is false
16:01:38.677 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.SaslServerPrincipal - Canonicalized address to 127.0.0.1
16:01:38.679 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Opening socket connection to server 127.0.0.1/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
16:01:38.680 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Socket connection established to 127.0.0.1/127.0.0.1:2181, initiating session
16:01:38.681 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Session establishment request sent on 127.0.0.1/127.0.0.1:2181
16:01:38.694 [main-SendThread(127.0.0.1:2181)] WARN org.apache.zookeeper.ClientCnxnSocket - Connected to an old server; r-o mode will be unavailable
16:01:38.695 [main-SendThread(127.0.0.1:2181)] INFO org.apache.zookeeper.ClientCnxn - Session establishment complete on server 127.0.0.1/127.0.0.1:2181, sessionid = 0x16b07ab1dee0008, negotiated timeout = 5000
16:01:40.352 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x16b07ab1dee0008 after 1ms
16:01:42.017 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x16b07ab1dee0008 after 0ms
16:01:43.684 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x16b07ab1dee0008 after 0ms
等待6秒以后
16:01:44.710 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x16b07ab1dee0008, packet:: clientPath:null serverPath:null finished:false header:: 1,1  replyHeader:: 1,80,0  request:: '/zksyn3,#746573745a6f6f6b6565706572,v{s{31,s{'world,'anyone}}},0  response:: '/zksyn3 
创建节点成功/zksyn3
16:01:44.711 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x16b07ab1dee0008 after 12ms
16:01:44.711 [main] DEBUG org.apache.zookeeper.ZooKeeper - Closing session: 0x16b07ab1dee0008
16:01:44.711 [main] DEBUG org.apache.zookeeper.ClientCnxn - Closing client for session: 0x16b07ab1dee0008
16:01:44.713 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x16b07ab1dee0008, packet:: clientPath:null serverPath:null finished:false header:: 2,-11  replyHeader:: 2,81,0  request:: null response:: null
16:01:44.713 [main] DEBUG org.apache.zookeeper.ClientCnxn - Disconnecting client for session: 0x16b07ab1dee0008
16:01:44.713 [main] INFO org.apache.zookeeper.ZooKeeper - Session: 0x16b07ab1dee0008 closed
16:01:44.713 [main-EventThread] INFO org.apache.zookeeper.ClientCnxn - EventThread shut down for session: 0x16b07ab1dee0008

 

 

5.关于创建zk节点的几种类型:

  

String create = zk.create("/zksyn3", "testZookeeper".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

 

 public String create(final String path, byte data[], List<ACL> acl,
            CreateMode createMode)
        throws KeeperException, InterruptedException
    {
        final String clientPath = path;
        PathUtils.validatePath(clientPath, createMode.isSequential());

        final String serverPath = prependChroot(clientPath);

        RequestHeader h = new RequestHeader();
        h.setType(ZooDefs.OpCode.create);
        CreateRequest request = new CreateRequest();
        CreateResponse response = new CreateResponse();
        request.setData(data);
        request.setFlags(createMode.toFlag());
        request.setPath(serverPath);
        if (acl != null && acl.size() == 0) {
            throw new KeeperException.InvalidACLException();
        }
        request.setAcl(acl);
        ReplyHeader r = cnxn.submitRequest(h, request, response, null);
        if (r.getErr() != 0) {
            throw KeeperException.create(KeeperException.Code.get(r.getErr()),
                    clientPath);
        }
        if (cnxn.chrootPath == null) {
            return response.getPath();
        } else {
            return response.getPath().substring(cnxn.chrootPath.length());
        }
    }

path:表示路径必须以"/" 开始

byte:创建节点的内容

acl:节点的记录或者标记(访问的权限该节点的)

createMode:节点的类型

public enum CreateMode {
    
    /**
     * The znode will not be automatically deleted upon client's disconnect.
     */
    PERSISTENT (0, false, false),//持久节点
    /**
    * The znode will not be automatically deleted upon client's disconnect,
    * and its name will be appended with a monotonically increasing number.
    */
    PERSISTENT_SEQUENTIAL (2, false, true),//有序持久节点
    /**
     * The znode will be deleted upon the client's disconnect.
     */
    EPHEMERAL (1, true, false),//临时节点
    /**
     * The znode will be deleted upon the client's disconnect, and its name
     * will be appended with a monotonically increasing number.
     */
    EPHEMERAL_SEQUENTIAL (3, true, true);//临时有序节点

 

临时节点在zk连接关闭断开以后,则节点信息消失,以上就是简单的java操作zookeeper的方式

 

posted on 2019-05-30 16:11  年少不知愁  阅读(1123)  评论(0编辑  收藏  举报