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 ...
随机推荐
- aspcms逻辑错误导致后台地址泄露
访问即可跳转后台地址: URL:http://www.xxx.org.cn/plug/oem/AspCms_OEMFun.asp 注入:plug/comment/commentList.asp?id= ...
- js 各种事件 如:点击事件、失去焦点、键盘事件等
事件驱动: 我们点击按钮 按钮去掉用相应的方法. demo: <input type="button" v ...
- shiro的基本认识及做一个简单的授权登陆的例子
先推荐一个网站,无意中发现的.感觉蛮好的. 推荐一套完整的Shiro Demo,免费的.Shiro Demo:http://www.sojson.com/shiroDemo已经部署到线上,地址是htt ...
- layui(三)——laypage组件常见用法总结
laypage 的使用非常简单,指向一个用于存放分页的容器,通过服务端得到一些初始值,即可完成分页渲染.核心方法: laypage.render(options) 来设置基础参数. 一.laypag ...
- C语言数据类型的转换(隐式转换)
算术运算符中的转换规则: double ←── float 高↑long↑unsigned↑int ←── char,short 低 注意: 图中横向箭头表示必须的转换,如两个float型数参加运算, ...
- ubuntu 配置minicom 进行串口开发
sudo apt-get install minicom sudo minicom -s Serial port setup Save setup as d ...
- html基本进阶知识【转】
inline和block的区别: 网页一般是两种元素组合起来的,一种是内联元素,也就是行内显示,加上width和height没效果.一种是区块元素,可以加上对应的width和height,通常使用在网 ...
- HDU 1098(条件满足 数学)
题意是问是否存在非负整数 a,使得任取非负整数 x,f(x) 能够被 65 整除,其中 f(x) = 5*x^13 + 13*x^5 + k*a*x,如存在,输出 a 的最小值,如不存在,输出 no. ...
- GeoGlobe Server使用问题收集
本人在做数字县区过程中,需要吉奥GeoGlobe Server发布数据,期间遇到些平台问题.故立此帖,作为参考. 1 字段限制: GeoGlobe 5.2部署在我的服务器Windows Server ...
- DosBox 的 DOSBOX.CONF 的详细配置说
1.首先下载 DOSbox 0.72 版. 2.下载完毕,开始安装.安装到任意目录均可.安装完毕会在开始菜单生成程序组,DOSBox.conf 文件是 DOSbox 的配置文件,保持默认配置就可 ...