Zookeeper学习笔记3
客户端的操作
zkCli.sh
ls /
[zookeeper]
get /
cZxid = 0x0
ctime = Thu Jan 01 08:00:00 CST 1970
mZxid = 0x0
mtime = Thu Jan 01 08:00:00 CST 1970
pZxid = 0x0
cversion = -1
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 0
numChildren = 1
create /test 123
Created /test
set /test 456
cZxid = 0x2
ctime = Wed Mar 28 11:20:40 CST 2018
mZxid = 0x3
mtime = Wed Mar 28 11:21:22 CST 2018
pZxid = 0x2
cversion = 0
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 3
numChildren = 0
delete /test
Java API
创建会话
public class ZkDemon4java implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
public void process(WatchedEvent watchedEvent) {
System.out.println("receive wathedEvent:" + watchedEvent);
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
countDownLatch.countDown();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
ZooKeeper zooKeeper = new ZooKeeper("192.168.2.192:2181", 5000, new ZkDemon4java());
System.out.println("zk status:" + zooKeeper.getState());
countDownLatch.await();
}
}
输出:
zk status:CONNECTING
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
使用sessionId,sessionPasswd
ZooKeeper zooKeeper = new ZooKeeper("192.168.2.192:2181", 5000, new ZkDemon4java());
System.out.println("zk status:" + zooKeeper.getState());
countDownLatch.await();
long sessionId = zooKeeper.getSessionId();
byte[] sessionPasswd = zooKeeper.getSessionPasswd();
zooKeeper = new ZooKeeper("192.168.2.192:2181", 5000, new ZkDemon4java(), sessionId, sessionPasswd);
zooKeeper = new ZooKeeper("192.168.2.192:2181", 5000, new ZkDemon4java(), sessionId, "123456".getBytes());
Thread.sleep(Integer.MAX_VALUE);
结果:
zk status:CONNECTING
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
receive wathedEvent:WatchedEvent state:Expired type:None path:null
receive wathedEvent:WatchedEvent state:Disconnected type:None path:null
receive wathedEvent:WatchedEvent state:Disconnected type:None path:null
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
Expired 是使用错误sessionPasswd的结果
至于结果中的不断地SyncConnected,Disconnected尚不清楚。
创建节点
同步执行:创建临时节点,临时顺序节点
//sync
String s = zooKeeper.create("/test1", "value1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println("success create path:" + s);
s = zooKeeper.create("/test1", "value1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println("success create path:" + s);
结果:
zk status:CONNECTING
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
success create path:/test1
success create path:/test10000000001
临时,顺序在zkCli用-e, -s指定,临时节点会在会话结束时删除,顺序节点会自动添加序号。
同步执行:
public class ZkDemon4java implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
public void process(WatchedEvent watchedEvent) {
System.out.println("receive wathedEvent:" + watchedEvent);
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
countDownLatch.countDown();
}
}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
ZooKeeper zooKeeper = new ZooKeeper("192.168.2.192:2181", 5000, new ZkDemon4java());
System.out.println("zk status:" + zooKeeper.getState());
countDownLatch.await();
IStringCallBack iStringCallBack = new ZkDemon4java().new IStringCallBack();
//async
zooKeeper.create("/test1", "value1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, iStringCallBack, "i am ctx");
zooKeeper.create("/test1", "value1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, iStringCallBack, "i am ctx");
zooKeeper.create("/test1", "value1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, iStringCallBack, "i am ctx");
Thread.sleep(Integer.MAX_VALUE);
}
class IStringCallBack implements AsyncCallback.StringCallback {
public void processResult(int i, String s, Object o, String s1) {
System.out.println("Create Path result resultCode:" + i + ",path:" + s + ",ctx:" + o.toString() + ",real path name:" + s1);
}
}
}
结果:
zk status:CONNECTING
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
Create Path result resultCode:0,path:/test1,ctx:i am ctx,real path name:/test1
Create Path result resultCode:-110,path:/test1,ctx:i am ctx,real path name:null
Create Path result resultCode:0,path:/test1,ctx:i am ctx,real path name:/test10000000009
删除节点
zooKeeper.delete("/test", -1);
其中version=-1表示不论节点的dataVersion是什么都删除,如果指定一个大于-1的数,则只当version不一样时不能删除。
读取数据
getChildren(同步)
public class ZkDemon4java implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static ZooKeeper zooKeeper;
public void process(WatchedEvent watchedEvent) {
System.out.println("receive wathedEvent:" + watchedEvent);
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
if (watchedEvent.getType() == Event.EventType.None && null == watchedEvent.getPath()) {
countDownLatch.countDown();
} else if (Event.EventType.NodeChildrenChanged == watchedEvent.getType()) {
try {
//if you need get advice again you must set watch:true
System.out.println("ReGet child:" + zooKeeper.getChildren(watchedEvent.getPath(), false));
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
zooKeeper = new ZooKeeper("192.168.2.192:2181", 5000, new ZkDemon4java());
System.out.println("zk status:" + zooKeeper.getState());
countDownLatch.await();
String path = "/zk_book";
zooKeeper.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//get children List and register Watch
System.out.println("get child result:" + zooKeeper.getChildren(path, new ZkDemon4java()));
zooKeeper.create(path + "/c1", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
zooKeeper.create(path + "/c2", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Thread.sleep(Integer.MAX_VALUE);
}
}
System.out.println("ReGet child:" + zooKeeper.getChildren(watchedEvent.getPath(), false));一次通知
zk status:CONNECTING
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
get child result:[]
receive wathedEvent:WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/zk_book
ReGet child:[c1]
System.out.println("ReGet child:" + zooKeeper.getChildren(watchedEvent.getPath(), true));多次通知
zk status:CONNECTING
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
get child result:[]
receive wathedEvent:WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/zk_book
ReGet child:[c1]
receive wathedEvent:WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/zk_book
ReGet child:[c1, c2]
getChildren(异步)
class ZkDemon4java implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static ZooKeeper zooKeeper;
public void process(WatchedEvent watchedEvent) {
System.out.println("receive wathedEvent:" + watchedEvent);
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
if (watchedEvent.getType() == Event.EventType.None && null == watchedEvent.getPath()) {
countDownLatch.countDown();
} else if (Event.EventType.NodeChildrenChanged == watchedEvent.getType()) {
try {
//if you need get advice again you must set watch:true
System.out.println("ReGet child:" + zooKeeper.getChildren(watchedEvent.getPath(), true));
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
zooKeeper = new ZooKeeper("192.168.2.192:2181", 5000, new ZkDemon4java());
System.out.println("zk status:" + zooKeeper.getState());
countDownLatch.await();
String path = "/zk_book";
zooKeeper.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//get children List and register Watch
zooKeeper.getChildren(path, true, new IChildren2Callback(), "i am ctx");
zooKeeper.create(path + "/c1", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
zooKeeper.create(path + "/c2", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Thread.sleep(Integer.MAX_VALUE);
}
}
class IChildren2Callback implements AsyncCallback.Children2Callback {
public void processResult(int i, String s, Object o, List<String> list, Stat stat) {
System.out.println("get children node result: result code:" + i + ",param path:" + s + ",ctx:" + o.toString() + ",children List:" + list + ",stat:" + stat);
}
}
结果:
zk status:CONNECTING
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
get children node result: result code:0,param path:/zk_book,ctx:i am ctx,children List:[],stat:211,211,1522231252330,1522231252330,0,0,0,0,3,0,211
receive wathedEvent:WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/zk_book
ReGet child:[c1]
receive wathedEvent:WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/zk_book
ReGet child:[c1, c2]
getData(同步)
public class ZkDemon4java implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static ZooKeeper zooKeeper;
public void process(WatchedEvent watchedEvent) {
System.out.println("receive wathedEvent:" + watchedEvent);
try {
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
if (watchedEvent.getType() == Event.EventType.None && null == watchedEvent.getPath()) {
countDownLatch.countDown();
} else if (Event.EventType.NodeDataChanged == watchedEvent.getType()) {
System.out.println("ReGet Data:" + zooKeeper.getData(watchedEvent.getPath(), true, new Stat()));
}
}
} catch (Exception e) {
e.toString();
}
}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
zooKeeper = new ZooKeeper("192.168.2.192:2181", 5000, new ZkDemon4java());
System.out.println("zk status:" + zooKeeper.getState());
countDownLatch.await();
String path = "/zk_book";
System.out.println("get data result:" + zooKeeper.getData(path, true, new Stat()));
zooKeeper.setData(path, "123".getBytes(), -1);
zooKeeper.setData(path, "123".getBytes(), -1);
Thread.sleep(Integer.MAX_VALUE);
}
}
结果:
zk status:CONNECTING
receive wathedEvent:WatchedEvent state:SyncConnected type:None path:null
get data result:[B@73f792cf
receive wathedEvent:WatchedEvent state:SyncConnected type:NodeDataChanged path:/zk_book
ReGet Data:[B@20d91839
receive wathedEvent:WatchedEvent state:SyncConnected type:NodeDataChanged path:/zk_book
ReGet Data:[B@2e1ee252
getData(异步)
略
下面的api如果异步比较简单就都省略
setData
package com.xh.zk.javaapi;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
/**
* Created by root on 3/28/18.
*/
public class ZkDemon4java implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static ZooKeeper zk;
public void process(WatchedEvent watchedEvent) {
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
if (Event.EventType.None == watchedEvent.getType() && watchedEvent.getPath() == null) {
countDownLatch.countDown();
}
}
}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
String connection = "192.168.2.192:2181";
String path = "/zk_book";
zk = new ZooKeeper(connection, 5000, new ZkDemon4java());
countDownLatch.await();
zk.create(path, "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
byte[] get_data = zk.getData(path, null, null);
Stat set_stat = zk.setData(path, "456".getBytes(), -1);
System.out.println(set_stat.getCzxid() + "," + set_stat.getMzxid() + "," + set_stat.getVersion());
Stat set_stat2 = zk.setData(path, "qqq".getBytes(), set_stat.getVersion());
System.out.println(set_stat2.getCzxid() + "," + set_stat2.getMzxid() + "," + set_stat2.getVersion());
Stat set_stat3 = zk.setData(path, "aaa".getBytes(), set_stat.getVersion());
System.out.println(set_stat3.getCzxid() + "," + set_stat3.getMzxid() + "," + set_stat3.getVersion());
Thread.sleep(Integer.MAX_VALUE);
}
}
结果:
13,14,1
13,15,2
Exception in thread "main" org.apache.zookeeper.KeeperException$BadVersionException: KeeperErrorCode = BadVersion for /zk_book
Version传入-1表示非原子操作,每次修改数据,版本号就递增,不一致就报错
exists
package com.xh.zk.javaapi;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
/**
* Created by root on 3/28/18.
*/
public class ZkDemon4java implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static ZooKeeper zk;
static String path = "/zk_book";
public void process(WatchedEvent watchedEvent) {
try {
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
if (Event.EventType.None == watchedEvent.getType() && watchedEvent.getPath() == null) {
countDownLatch.countDown();
} else if (Event.EventType.NodeCreated == watchedEvent.getType()) {
System.out.println(watchedEvent.getPath() + " NodeCreated");
zk.exists(path, true);
} else if (Event.EventType.NodeDataChanged == watchedEvent.getType()) {
System.out.println(watchedEvent.getPath() + " NodeDataChanged");
zk.exists(path, true);
} else if (Event.EventType.NodeDeleted == watchedEvent.getType()) {
System.out.println(watchedEvent.getPath() + " NodeDeleted");
zk.exists(path, true);
}
}
} catch (Exception e) {
}
}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
String connection = "192.168.2.192:2181";
zk = new ZooKeeper(connection, 5000, new ZkDemon4java());
countDownLatch.await();
zk.exists(path, true);
zk.create(path, "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create(path + "/abc", "abc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.setData(path, "world".getBytes(), -1);
zk.delete(path + "/abc", -1);
zk.delete(path, -1);
Thread.sleep(Integer.MAX_VALUE);
}
}
结果:
/zk_book NodeCreated
/zk_book NodeDataChanged
/zk_book NodeDeleted
无论节点是否存在,都可用exists监听,对该节点增删改都会通知,但是不会通知其子节点的操作
addAuthInfo
创建一个需要权限访问的节点
public class ZkDemon4java implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static ZooKeeper zk_auth;
static String path = "/zk_book";
public void process(WatchedEvent watchedEvent) {
}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
String connection = "192.168.2.192:2181";
zk_auth = new ZooKeeper(connection, 5000, new ZkDemon4java());
zk_auth.addAuthInfo("digest", "foo:true".getBytes());
zk_auth.create(path, "hello".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
Thread.sleep(Integer.MAX_VALUE);
}
}
创建几个客户端访问之前的节点,分别是 :没有权限信息,错误权限信息,正确权限信息
/**
* no auth info
*/
zk_1 = new ZooKeeper(connection, 5000, new Zk1());
zk_1.getData(path, false, null);
Thread.sleep(Integer.MAX_VALUE);
结果:
Exception in thread "main" org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode = NoAuth for /zk_book
/**
* wrong auth info
*/
zk_2 = new ZooKeeper(connection, 5000, new Zk2());
zk_2.addAuthInfo("digest", "foo:true121".getBytes());
zk_2.getData(path, false, null);
Thread.sleep(Integer.MAX_VALUE);
结果:
Exception in thread "main" org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode = NoAuth for /zk_book
/**
* right auth info
*/
zk_3 = new ZooKeeper(connection, 5000, new Zk3());
zk_3.addAuthInfo("digest", "foo:true".getBytes());
byte[] zk_3Data = zk_3.getData(path, false, null);
System.out.println(zk_3Data);
Thread.sleep(Integer.MAX_VALUE);
结果:
[B@37bba400
Zookeeper学习笔记3的更多相关文章
- ZooKeeper 学习笔记
ZooKeeper学习笔记 1. zookeeper基本概念 zookeeper是一个分布式的,开放源码的分布式应用程序协调服务,是hadoop和Habase的重要组件,是为分布式应用提供一致性服 ...
- ZooKeeper学习笔记(二)——内部原理
zookeeper学习笔记(二)--内部原理 1. zookeeper的节点的类型 总的来说可以分为持久型和短暂型,主要区别如下: 持久:客户端与服务器端断开连接的以后,创建的节点不会被删除: 持久化 ...
- ZooKeeper学习笔记(一)——概述
zookeeper学习笔记(一)--概述 1. 概述 Zookeeper是一个开源的分布式的,为分布式应用提供协调服务的Apache项目.zookeeper从设计模式的角度来理解:是一个基于观察者设计 ...
- Zookeeper学习笔记(中)
Zookeeper学习笔记(中) Zookeeper的基本原理和基本实现 深入了解ZK的基本原理 ZK的一致性: ZAB 协议: Zookeeper 原子消息广播协议 ZK通过选举保证 leader ...
- Zookeeper学习笔记(上)
Zookeeper学习笔记 本篇主要是一些基本的介绍和API的使用介绍, 有些只是记录了知识点,而没有完全在笔记中详细解释, 需要自行查找资料补充相关概念 主要参考了课程中的内容: Zookeeper ...
- ZooKeeper学习笔记一:集群搭建
作者:Grey 原文地址:ZooKeeper学习笔记一:集群搭建 说明 单机版的zk安装和运行参考:https://zookeeper.apache.org/doc/r3.6.3/zookeeperS ...
- ZooKeeper学习笔记三:使用ZooKeeper实现一个简单的配置中心
作者:Grey 原文地址:ZooKeeper学习笔记三:使用ZooKeeper实现一个简单的配置中心 前置知识 完成ZooKeeper集群搭建以及熟悉ZooKeeperAPI基本使用 需求 很多程序往 ...
- ZooKeeper学习笔记二:API基本使用
Grey ZooKeeper学习笔记二:API基本使用 准备工作 搭建一个zk集群,参考ZooKeeper学习笔记一:集群搭建. 确保项目可以访问集群的每个节点 新建一个基于jdk1.8的maven项 ...
- ZooKeeper学习笔记四:使用ZooKeeper实现一个简单的分布式锁
作者:Grey 原文地址: ZooKeeper学习笔记四:使用ZooKeeper实现一个简单的分布式锁 前置知识 完成ZooKeeper集群搭建以及熟悉ZooKeeperAPI基本使用 需求 当多个进 ...
- Zookeeper学习笔记(下)
这是ZK学习笔记的下篇, 主要希望可以分享一些 ZK 的应用以及其应用原理 我本人的学习告一段落, 不过还遗留了一些ZK相关的任务开发和性能测试的任务, 留待以后完成之后再通过其他文章来进行分享了 Z ...
随机推荐
- Qt ------ QDir 路径
QDir::currentPath() 获取当前路径 QDir::toNativeSeparators 把windows下的路径转换为Qt可以识别的路径,如"C:/Users/Adminis ...
- 全局拦截各种http请求
http请求无非就是ajax.src.href.表单 function hookAJAX() { XMLHttpRequest.prototype.nativeOpen = XMLHttpReques ...
- 集成学习算法汇总----Boosting和Bagging(推荐AAA)
sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003& ...
- Redis之Transactions(事物)
你问我Redis支不支持事物?告诉你,Redis对事物的支持是部分支持(对比关系型数据库,没有强一致性) 定义:一个队列.一次性.顺序的.排他性的执行一系列命令 常用命令: DISCARD 取消事物, ...
- Nginx记录-Nginx基础(转载)
1.Nginx常用功能 1.Http代理,反向代理:作为web服务器最常用的功能之一,尤其是反向代理. Nginx在做反向代理时,提供性能稳定,并且能够提供配置灵活的转发功能.Nginx可以根据不同的 ...
- Windows下安装Mysql5.7
版本如下: Windows10 Mysql5.7.18 下载地址:https://dev.mysql.com/downloads/mysql/ 本人解压到了:D:\Program Files (x86 ...
- Android几个比较有用的插件
1.Android Drawable Importer 2.Android ButterKnife Zelezny 使用方法,在SetContentView上右键,Generate 3.Androi ...
- Div Height设置高度后不能自适应
解决方法$("#div1").css("height", "");
- Tippy.js – 轻量的 Javascript Tooltip 工具库
工具提示(Tooltip)在网站中的一个小功能,但却有很重要的作用,常用于显示一些温馨的提示信息.如果网站中的工具提示功能做得非常有创意的话能够加深用户对网站印象.Tippy.js 是一款帮助你快速创 ...
- 求f(n)=[n/1]+[n/2]+---+[n/n]的值 简单杂题
这种小题首先根据 n/1+n/2+n/3+--+n/n=nlogn+欧拉常数r 可以知道 1e12的范围也不会爆longlong,不需要写高精度(到现在都不会写) 再根据数据范围可知O(n)级别的暴力 ...