Zookeeper客户端使用

一、使用原生zookeeper

在pom.xml中加入依赖

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

直接上代码:

 /**
* Project Name:mk-project <br>
* Package Name:com.suns.zookeeper <br>
*
* @author mk<br>
* Date:2018-10-31 9:09 <br>
*/ package com.suns.zookeeper; import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat; import java.util.List;
import java.util.concurrent.CountDownLatch; /**
* 原生的zookeeper客户端
* 1.连接是异步的,使用时需要注意。增加watcher,监听事件如果为SyncConnected,那么才做其他的操作。(利用CountDownLatch控制)
* 2.监听事件是一次性的,如果操作多次需要注册多次(可以通过getData等方法)
* ClassName: ZookeeperNative <br>
* Description: <br>
* @author mk
* @Date 2018-10-31 9:09 <br>
* @version
*/
public class ZookeeperNative { public static final String connect = "127.0.0.1:2181";
private static ZooKeeper zookeeper = null;
private static CountDownLatch cdl = new CountDownLatch(0);
private static String nodePath = "/native1";
private static String nodeChildPath = "/native1/n1/n11/n111/n1111"; public static void main(String[] args) throws Exception { //初始化
init(connect,5000); //新增
create(nodePath,"n1");
//递归新增
createRecursion(nodeChildPath,"n1"); //查询
query(nodePath); //修改
update(nodePath,"n11"); //单个节点删除
// delete(nodePath);
//递归删除
deleteRecursion(nodePath);
} private static void deleteRecursion(String nodePath) throws KeeperException, InterruptedException {
Stat exists = zookeeper.exists(nodePath, true);
if(null == exists){
System.out.println(nodePath+"不存在");
return ;
} List<String> list = zookeeper.getChildren(nodePath, true);
if(null == list || list.size() == 0){
delete(nodePath);
String parentPath = nodePath.substring(0,nodePath.lastIndexOf("/"));
System.out.println("parentPath="+parentPath);
if(!"".equals(parentPath)){
deleteRecursion(parentPath);
}
}else{
for(String child : list){
deleteRecursion(nodePath+"/"+child);
}
}
} private static void delete(String path) throws KeeperException, InterruptedException {
query(path);//为了让watcher能被监听,在这里查询一次
zookeeper.delete(path,-1);
System.out.println("delete:"+"["+path+"]");
} private static void update(String path, String data) throws KeeperException, InterruptedException {
Stat stat = zookeeper.setData(path, data.getBytes(), -1);//versoin=-1代表不记录版本
System.out.println("setData:"+"["+path+"],stat:"+stat);
} private static void query(String path) throws KeeperException, InterruptedException {
Stat stat = new Stat();
byte[] data = zookeeper.getData(path, true, stat);
System.out.println("query:"+"["+path+"],result:"+new String(data) + ",stat:"+stat);
} private static void createRecursion(String path,String data) throws KeeperException, InterruptedException {
if(null == path || "".equals(path)){
System.out.println("节点["+path+"]为空");
return;
}
String paths[] = path.substring(1,path.length()).split("/");
for(int i=0;i<paths.length;i++){
String childPath = "";
for(int j=0;j<=i;j++){
childPath += "/" + paths[j];
}
create(childPath,data);
} Stat exists = zookeeper.exists(path, true);
if(null != exists){
System.out.println("节点["+path+"]已存在,不能新增");
return;
}
String result = zookeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("create:"+"["+path+"-->"+data+"],result:"+result);
} private static void create(String path,String data) throws KeeperException, InterruptedException {
Stat exists = zookeeper.exists(path, true);
if(null != exists){
System.out.println("节点["+path+"]已存在,不能新增");
return;
}
String result = zookeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("create:"+"["+path+"-->"+data+"],result:"+result);
} private static void init(final String connectStr, int sessionTimeout) throws Exception {
// zookeeper = new ZooKeeper(connectStr, sessionTimeout, null);
//由于zookeeper连接是异步的,如果new ZooKeeper(connectStr, sessionTimeout, null)完之后马上使用,有可能会报错。
//解决办法:增加watcher,监听事件如果为SyncConnected,那么才做其他的操作。(利用CountDownLatch控制)
zookeeper = new ZooKeeper(connectStr, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
if(watchedEvent.getState() == Event.KeeperState.SyncConnected) {
// System.out.println("zookeeper已连接["+connectStr+"]成功");
cdl.countDown();
}
if(watchedEvent.getType() == Event.EventType.NodeCreated){
System.out.println("zookeeper有新节点创建"+watchedEvent.getPath());
}
if(watchedEvent.getType() == Event.EventType.NodeDataChanged){
System.out.println("zookeeper有节点数据变化"+watchedEvent.getPath());
}
if(watchedEvent.getType() == Event.EventType.NodeDeleted){
System.out.println("zookeeper有节点被删除"+watchedEvent.getPath());
}
if(watchedEvent.getType() == Event.EventType.NodeChildrenChanged){
System.out.println("zookeeper有子节点变化"+watchedEvent.getPath());
}
}
});
cdl.await();
System.out.println("init start :" +zookeeper);
} }

运行结果:

Zookeeper客户端使用(使用原生zookeeper)的更多相关文章

  1. Zookeeper系列三:Zookeeper客户端的使用(Zookeeper原生API如何进行调用、ZKClient、Curator)和Zookeeper会话

    一.Zookeeper原生API如何进行调用 准备工作: 首先在新建一个maven项目ZK-Demo,然后在pom.xml里面引入zk的依赖 <dependency> <groupI ...

  2. ZooKeeper客户端原生API的使用以及ZkClient第三方API的使用

    这两部分内容的介绍主要讲的是节点及节点内容和子节点的操作,并且讲解的节点的事件监听以及ACL授权 ZooKeeper客户端原生API的使用 百度网盘地址: http://pan.baidu.com/s ...

  3. Zookeeper客户端使用(使用Curator)

    Zookeeper客户端(使用Curator) 三.使用curator客户端 在pom.xml中加入依赖 <dependency> <groupId>org.apache.cu ...

  4. Zookeeper客户端使用(使用zkclient)

    Zookeeper客户端使用 二.使用zkclient 在pom.xml中加入依赖 <dependency> <groupId>com.101tec</groupId&g ...

  5. zookeeper客户端使用原生JavaApi操作节点

    1.引入依赖 <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zook ...

  6. Zookeeper客户端Curator基本API

    在使用zookeper的时候一般不使用原生的API,Curator,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连.反复注册Watcher和NodeExistsExceptio ...

  7. Zookeeper客户端Curator的使用,简单高效

    Curator是Netflix公司开源的一个Zookeeper客户端,与Zookeeper提供的原生客户端相比,Curator的抽象层次更高,简化了Zookeeper客户端的开发量. 1.引入依赖: ...

  8. Zookeeper客户端Curator使用详解

    Zookeeper客户端Curator使用详解 前提 最近刚好用到了zookeeper,做了一个基于SpringBoot.Curator.Bootstrap写了一个可视化的Web应用: zookeep ...

  9. 7.5 zookeeper客户端curator的基本使用 + zkui

    使用zookeeper原生API实现一些复杂的东西比较麻烦.所以,出现了两款比较好的开源客户端,对zookeeper的原生API进行了包装:zkClient和curator.后者是Netflix出版的 ...

随机推荐

  1. 使用tensorflow.data.Dataset构造batch数据集(具体用法在下一篇博客介绍)

    import tensorflow as tf import numpy as np def _parse_function(x): num_list = np.arange(10) return n ...

  2. 无法在WEB服务器上启动调试,Web 服务器配置不正确

    访问IIS元数据库失败 思考可能是次序出了问题,解决 1.打开CMD,进入 C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 2.输入 aspnet_regi ...

  3. OpenStack 虚拟机冷/热迁移的实现原理与代码分析

    目录 文章目录 目录 前文列表 冷迁移代码分析(基于 Newton) Nova 冷迁移实现原理 热迁移代码分析 Nova 热迁移实现原理 向 libvirtd 发出 Live Migration 指令 ...

  4. self-training and co-training

    半指导学习(Semi-supervised Learning)的概念说起来一点儿也不复杂,即从同时含有标注数据和未标注数据的训练集中学习模型.半指导学习是介于有指导学习与无指导学习之间的一种机器学习方 ...

  5. 网易云课堂_C++程序设计入门(下)_第10单元:月映千江未减明 – 模板_第10单元 - 单元作业:OJ编程 - 创建数组类模板

    第10单元 - 单元作业:OJ编程 - 创建数组类模板 查看帮助 返回   温馨提示: 1.本次作业属于Online Judge题目,提交后由系统即时判分. 2.学生可以在作业截止时间之前不限次数提 ...

  6. [转] margin负值的探讨

    原文:  margin负值-权威指南 [http://www.csswang.com/exp/cssexp/3863.html] static元素是没有设定成浮动的元素,下图说明了负margin对st ...

  7. Flutter异步Future

    一.认识Future 1.创建Future void testFuture(){ Future future = new Future(() => null); future.then((_){ ...

  8. java:Oracle(聚合函数,多表查询,表之间的关系)

    1.聚合函数 --max,min,sum,avg,count,nvl(,) -- max:最大值 -- max既能取数字的最大值,也可以取字符串的最大值(英文字母排列顺序),根据场景实际意义来看,最好 ...

  9. DSP28335 GPIO学习

    根据网络资料以及以下两篇博客整理 http://blog.sina.com.cn/s/blog_86a6035301017rr7.html http://blog.csdn.net/hmf123578 ...

  10. sql语言(mysql)

    一.SQL语言 1.DDL (Data Definition Language) 数据库定义语言 2.DML(Data Manipulation Language) 数据库操作语言 3.DQL (Da ...