创建会话

  • 建立简单连接
/*** 测试创建Zk会话* Created by liuhuichao on 2017/7/25.*/
public class ZooKeeper_Constructor_Usage_Simple implements Watcher {private static CountDownLatch connectedSemaphore=new CountDownLatch(1);public static void main(String[] args) throws Exception{ZooKeeper zk=new ZooKeeper("192.168.99.215:2181",5000,new ZooKeeper_Constructor_Usage_Simple());System.out.println(zk.getState());connectedSemaphore.await();System.out.println("zk session established");}/*** 处理来自ZK服务端的watcher通知* @param watchedEvent*/@Overridepublic void process(WatchedEvent watchedEvent) {System.out.println("receive watched event:"+watchedEvent);if(Event.KeeperState.SyncConnected==watchedEvent.getState()){connectedSemaphore.countDown();//解除等待阻塞}}
}
  • 复用会话
/*** 复用sessionId和sessionPassword的会话* Created by liuhuichao on 2017/7/25.*/
public class ZooKeeper_Constructor_Usage_With_sid_password implements Watcher {private static CountDownLatch connectedSemaphore=new CountDownLatch(1);@Overridepublic void process(WatchedEvent watchedEvent) {System.out.println("receive watched event:"+watchedEvent);if(Event.KeeperState.SyncConnected==watchedEvent.getState()){connectedSemaphore.countDown();}}public static void main(String[] args) throws Exception{ZooKeeper zooKeeper=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_Constructor_Usage_With_sid_password());connectedSemaphore.await();long sessionId=zooKeeper.getSessionId();byte[] password=zooKeeper.getSessionPasswd();/**使用错误的sessionID跟sessionPwd连连接测试[192.168.99.215 lhc-centos0]**/ZooKeeper zkWrong=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_Constructor_Usage_With_sid_password(),1l,"lhc".getBytes());/**使用正确的来进行连接**/ZooKeeper zkTrue=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_Constructor_Usage_With_sid_password(),sessionId,password);Thread.sleep(Integer.MAX_VALUE);}
}

创建节点

  • 使用同步API创建节点
/*** 使用同步API创建一个节点* Created by liuhuichao on 2017/7/25.*/
public class ZooKeeper_Create_API_Sync_Usage implements Watcher {private static CountDownLatch connectedSemaphore=new CountDownLatch(1);@Overridepublic void process(WatchedEvent watchedEvent) {if(Event.KeeperState.SyncConnected==watchedEvent.getState()){connectedSemaphore.countDown();}}public static void main(String[] args) throws Exception{ZooKeeper zooKeeper=new ZooKeeper("192.168.99.215:2181",5000,new ZooKeeper_Create_API_Sync_Usage());connectedSemaphore.await();String path1=zooKeeper.create("/zk-test1","lhc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);//临时结点System.out.println(path1+" 创建成功!");String path2=zooKeeper.create("/zk-test2","lllhhhhhhhhhhhhhhhhc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);System.out.println(path2+"  创建成功!");}
}
  • 使用异步API创建一个节点
/*** 使用异步API创建一个节点* Created by liuhuichao on 2017/7/25.*/
public class ZooKeeper_Create_API_ASync_Usage implements Watcher{private static CountDownLatch connectedSamphore=new CountDownLatch(1);@Overridepublic void process(WatchedEvent watchedEvent) {if(watchedEvent.getState()== Event.KeeperState.SyncConnected){connectedSamphore.countDown();}}public static void main(String[] args) throws Exception{ZooKeeper zk1=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_Create_API_ASync_Usage());connectedSamphore.await();zk1.create("/zk-test-1","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT,new IStringCallBack(),"i am a context");zk1.create("/zk-test-2","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT,new IStringCallBack(),"i am a context");zk1.create("/zk-test-3","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT_SEQUENTIAL,new IStringCallBack(),"i am a context");Thread.sleep(Integer.MAX_VALUE);}
}/*** Created by liuhuichao on 2017/7/26.*/
public class IStringCallBack implements AsyncCallback.StringCallback{@Overridepublic void processResult(int rc, String path, Object ctx, String name) {System.out.println("result:"+rc+"; path="+path+" ctx="+ctx+" name = "+name);}
}

删除节点

/*** 删除zk的持久结点* Created by liuhuichao on 2017/7/26.*/
public class ZooKeeperDeleteNode implements Watcher {private  static CountDownLatch conntedSamphore=new CountDownLatch(1);@Overridepublic void process(WatchedEvent watchedEvent) {if(Event.KeeperState.SyncConnected==watchedEvent.getState()){conntedSamphore.countDown();}}public static void main(String[] args) throws Exception{/**同步删除节点**/ZooKeeper zooKeeper=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeperDeleteNode());conntedSamphore.await();zooKeeper.delete("/zk-test-30000000014",0);}}

读取数据

  • 使用同步API获取子节点列表
/***获取结点-同步* Created by liuhuichao on 2017/7/26.*/
public class ZooKeeper_GetChildren_API_Sync_Usage implements Watcher {private  static CountDownLatch conntedSamphore=new CountDownLatch(1);private static ZooKeeper zooKeeper=null;@Overridepublic void process(WatchedEvent watchedEvent) {if(Event.KeeperState.SyncConnected==watchedEvent.getState()){conntedSamphore.countDown();}else if(watchedEvent.getType()== Event.EventType.NodeChildrenChanged){try {System.out.println("--------------------------------------reget children:"+zooKeeper.getChildren(watchedEvent.getPath(),true));} catch (KeeperException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) throws Exception{String path="/zk-test-1";zooKeeper=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_GetChildren_API_Sync_Usage());conntedSamphore.await();zooKeeper.create(path+"/test1","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);List<String> childrenList=zooKeeper.getChildren(path,true);System.out.println(childrenList);zooKeeper.create(path+"/test2","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);Thread.sleep(Integer.MAX_VALUE);}}
  • 使用异步API获取子节点列表
*** 异步获取结点* Created by liuhuichao on 2017/7/26.*/
public class ZooKeeper_GetChildren_API_ASync_Usage implements Watcher {private static CountDownLatch connectedSemphore=new CountDownLatch(1);private static ZooKeeper zk=null;@Overridepublic void process(WatchedEvent watchedEvent) {if(Event.KeeperState.SyncConnected==watchedEvent.getState()){connectedSemphore.countDown();}else if(watchedEvent.getType()== Event.EventType.NodeChildrenChanged){try {System.out.println("node changed===="+zk.getChildren(watchedEvent.getPath(),true));} catch (KeeperException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) throws Exception{String path="/zk-test-1";zk=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_GetChildren_API_ASync_Usage());connectedSemphore.await();zk.create(path+"/test3","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);zk.getChildren(path,true,new ICChild2Callback(),null);Thread.sleep(Integer.MAX_VALUE);}}/*** 异步获取结点回调接口* Created by liuhuichao on 2017/7/26.*/
public class ICChild2Callback implements AsyncCallback.Children2Callback{@Overridepublic void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {System.out.println("get children zonde result:[reponse code:"+rc+" path="+path+" ctx="+ctx+"  childrenlist="+children+" stat="+stat);}
}
  • 使用同步API获取结点数据
/**** 同步获取数据* Created by liuhuichao on 2017/7/27.*/
public class GetData_API_Sync_Usage  implements Watcher{private static CountDownLatch conntedSamphore=new CountDownLatch(1);private static ZooKeeper zk=null;private static Stat stat=new Stat();@Overridepublic void process(WatchedEvent watchedEvent) {if(Event.KeeperState.SyncConnected==watchedEvent.getState()){conntedSamphore.countDown();}else if(watchedEvent.getType()== Event.EventType.NodeCreated){System.out.println("node changed:"+watchedEvent.getPath());}}public static void main(String[] args) throws Exception{String path="/test-1";zk =new ZooKeeper("rc-zkp-datn-rse-nmg-ooz-woasis:2181",5000,new GetData_API_Sync_Usage());conntedSamphore.await();System.out.println("zk-19 连接成功!");//zk.create(path+"/lhc", "".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);List<String> children=zk.getChildren(path,new GetData_API_Sync_Usage());System.out.println("children node:"+children);zk.setData(path+"/lhc","memeda".getBytes(),-1);byte[] nodeValue=zk.getData(path+"/lhc",true,stat);System.out.println(new String(nodeValue));}
}
  • 使用异步API获取结点数据
/**** 同步/异步获取数据* Created by liuhuichao on 2017/7/27.*/
public class GetData_API_Sync_Usage  implements Watcher{private static CountDownLatch conntedSamphore=new CountDownLatch(1);private static ZooKeeper zk=null;private static Stat stat=new Stat();@Overridepublic void process(WatchedEvent watchedEvent) {if(Event.KeeperState.SyncConnected==watchedEvent.getState()){conntedSamphore.countDown();}else if(watchedEvent.getType()== Event.EventType.NodeCreated){System.out.println("node changed:"+watchedEvent.getPath());}}public static void main(String[] args) throws Exception{String path="/test-1";zk =new ZooKeeper("rc-zkp-datn-rse-nmg-ooz-woasis:2181",5000,new GetData_API_Sync_Usage());conntedSamphore.await();System.out.println("zk-19 连接成功!");//zk.create(path+"/lhc", "".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);List<String> children=zk.getChildren(path,new GetData_API_Sync_Usage());System.out.println("children node:"+children);zk.setData(path+"/lhc","lllhc".getBytes(),-1);zk.getData(path+"/lhc",true,new IDataCallback(),null);//异步获取数据Thread.sleep(Integer.MAX_VALUE);}
}/*** 异步获取node数据回调* Created by liuhuichao on 2017/7/27.*/
public class IDataCallback implements AsyncCallback.DataCallback {@Overridepublic void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {System.out.println("rc="+rc+" ;path="+path+" ;ctx="+ctx+" ;data="+data+" ;stat="+stat);System.out.println("string data="+new String(data));System.out.println("max version="+stat.getVersion());}
}

更新数据

  • 同步设置数据
  zk.setData(path+"/lhc","lllhc".getBytes(),-1);//同步设置数据
  • 异步设置数据
/**** 同步/异步获取数据* Created by liuhuichao on 2017/7/27.*/
public class GetData_API_Sync_Usage  implements Watcher{private static CountDownLatch conntedSamphore=new CountDownLatch(1);private static ZooKeeper zk=null;private static Stat stat=new Stat();@Overridepublic void process(WatchedEvent watchedEvent) {if(Event.KeeperState.SyncConnected==watchedEvent.getState()){conntedSamphore.countDown();}else if(watchedEvent.getType()== Event.EventType.NodeCreated){System.out.println("node changed:"+watchedEvent.getPath());}}public static void main(String[] args) throws Exception{String path="/test-1";zk =new ZooKeeper("rc-zkp-datn-rse-nmg-ooz-woasis:2181",5000,new GetData_API_Sync_Usage());conntedSamphore.await();System.out.println("zk-19 连接成功!");//zk.create(path+"/lhc", "".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);List<String> children=zk.getChildren(path,new GetData_API_Sync_Usage());System.out.println("children node:"+children);//zk.setData(path+"/lhc","lllhc".getBytes(),-1);//同步设置数据zk.setData(path+"/lhc","lhc".getBytes(),-1,new IStatCallback(),null);zk.getData(path+"/lhc",true,new IDataCallback(),null);//异步获取数据Thread.sleep(Integer.MAX_VALUE);}
}/*** 异步设置数据回调接口* Created by liuhuichao on 2017/7/27.*/
public class IStatCallback implements AsyncCallback.StatCallback{@Overridepublic void processResult(int rc, String path, Object ctx, Stat stat) {System.out.println("rc="+rc+" ;path="+path+" ;ctx="+ctx+" ;stat="+stat);if(rc==0){System.out.println("数据设置成功!");}}
}

检测节点是否存在


/*** 检测zk node* Created by liuhuichao on 2017/7/27.*/
public class Exist_API_Sync_Usage implements Watcher{private static CountDownLatch connetedSamphore=new CountDownLatch(1);private static ZooKeeper zk=null;@Overridepublic void process(WatchedEvent watchedEvent) {if(Event.KeeperState.SyncConnected==watchedEvent.getState()){connetedSamphore.countDown();}else if(Event.EventType.NodeCreated==watchedEvent.getType()){System.out.println("node created=="+watchedEvent.getPath());}else if(Event.EventType.NodeDataChanged==watchedEvent.getType()){System.out.println("node changed=="+watchedEvent.getPath());}else if(Event.EventType.NodeDeleted==watchedEvent.getType()){System.out.println("node deleted=="+watchedEvent.getPath());}}public static void main(String[] args)throws Exception {String path="/test-1";zk =new ZooKeeper("rc-zkp-datn-rse-nmg-ooz-woasis:2181",5000,new Exist_API_Sync_Usage());connetedSamphore.await();System.out.println("zk-19 连接成功!");Stat stat=zk.exists(path,new Exist_API_Sync_Usage());System.out.println("stat="+stat==null?"为空":"不为空");zk.setData(path,"".getBytes(),-1);Thread.sleep(Integer.MAX_VALUE);}
}

Java API操作ZK node相关推荐

  1. Apache ZooKeeper - 使用原生的API操作ZK

    文章目录 概述 maven依赖 验证 测试基类 ZK构造函数参数 connectString:ZooKeeper服务器列表 sessionTimeout:会话的超时时间, "毫秒" ...

  2. Hbase java API操作(模板代码)

    Hbase java API操作 1 创建maven工程 导入jar包 <repositories><repository><id>cloudera</id& ...

  3. 大数据技术之_20_Elasticsearch学习_01_概述 + 快速入门 + Java API 操作 + 创建、删除索引 + 新建、搜索、更新删除文档 + 条件查询 + 映射操作

    大数据技术之_20_Elasticsearch学习_01 一 概述 1.1 什么是搜索? 1.2 如果用数据库做搜索会怎么样? 1.3 什么是全文检索和 Lucene? 1.4 什么是 Elastic ...

  4. 大数据技术之_20_Elasticsearch学习_01_概述 + 快速入门 + Java API 操作 + 创建、删除索引 + 新建、搜索、更新删除文档 + 条件查询 + 映射操作...

    一 概述1.1 什么是搜索?1.2 如果用数据库做搜索会怎么样?1.3 什么是全文检索和 Lucene?1.4 什么是 Elasticsearch?1.5 Elasticsearch 的适用场景1.6 ...

  5. kafka详解(JAVA API操作kafka、kafka原理、kafka监控)-step2

    1.JAVA API操作kafka  修改Windows的Host文件: 目录:C:\Windows\System32\drivers\etc (win10) 内容: 192.168.40.150 k ...

  6. MongoDB Java API操作很全的整理以及共享分片模式下的常见操作整理

    MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,一般生产上建议以共享分片的形式来部署. 但是MongoDB官方也提供了其它语言的客户端操作API.如下图所示: 提供了C.C++ ...

  7. 2021年大数据ZooKeeper(五):ZooKeeper Java API操作

    目录 ZooKeeper Java API操作 引入maven坐标 节点的操作 ZooKeeper Java API操作 这里操作Zookeeper的JavaAPI使用的是一套zookeeper客户端 ...

  8. Kafka系列三 java API操作

    使用java API操作kafka 1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xs ...

  9. Hadoop详解(四):HDFS shell操作和Java API操作

    1. HDFS环境准备 1.1 HDFS的格式化与启动 HDFS配置完之后就可以对其进行格式化操作.在NameNode所在机器上执行如下命令进行HDFS的格式化操作: hadoop namenode ...

最新文章

  1. html css 显示数值_【CSS纯技术】20.03.05-CSS渲染的原理
  2. springboot整个cas_SpringBoot集成SpringSecurity+CAS
  3. mysql 常用操作
  4. Database之SQL:自定义创建数据库的各种表demo集合(以方便理解和分析sql的各种增删改查语法的具体用法)
  5. SQL学习---第一章
  6. php 判断3个数谁最小,Python编程学习之如何判断3个数的大小
  7. 下载的java游戏怎么运行不了_java运行环境下载
  8. win11华为的电脑管家错误怎么办 Windows11华为电脑管家错误的解决方法
  9. 指针常量和常量指针的区别
  10. C语言基础项目:200 行代码实现贪吃蛇,思路+源码详解
  11. jmeter的HTTP请求
  12. appium java模拟微信登录,使用Appium 测试微信小程序和微信公众号方法
  13. 我真要戒游戏了毒奶粉再见!
  14. 微信公众号文章怎么搞成html,微信公众号文章如何排版才能更好看(附教程)...
  15. cocos creator3.3.0休闲游戏(云浮消消乐)源码H5+安卓+IOS三端源码
  16. 利用纯CSS实现条纹背景
  17. IT猎头首秀-希望认识更多的程序员朋友
  18. BlueTooth: 什么是蓝牙(Bluetooth)
  19. 微信小程序:大红喜庆版UI猜灯谜又叫猜字谜
  20. 海思IPC平台快速拔插SD卡会出现SD卡不识别解决方法

热门文章

  1. Flink实时仓库-DWS层(关键词搜索分析-自定义函数,窗口操作,FlinkSql设置水位线,保存数据到Clickhouse)模板代码
  2. 字体个人商用构成侵权吗
  3. “私车公用”下 事故责任承担
  4. 【虚拟仿真】Unity3D中实现控制物体的旋转、移动、缩放
  5. Android studio安装与配置
  6. 02_字符设备驱动开发
  7. 从零开始搭建4G DTU设备对应的云平台(一)
  8. 达人评测 i5 13500h和i9 12900h选哪个好 酷睿i513500h和i912900h差距
  9. 启动计算机 页面文件配置问题,计算机启动出现了页面文件配置问题是什么原因 如何解决...
  10. 解除R中从github上下载包API限制的问题(Error: Failed to install ‘unknown package‘ from GitHub: HTTP error 403. )