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. 全面解读php-php会话控制技术

    一.PHP会话控制技术 1.为什么要使用会话控制技术? 因为http协议是无状态协议,所以同一个用户在请求同一个页面两次的时候,http协议不会认为这两次请求都来自于同一个用户,会把它们当做是两次请求 ...

  2. 【转】c语言动态与静态分配

    https://blog.csdn.net/qq_43519310/article/details/85274836 https://blog.csdn.net/qq_38906523/article ...

  3. Promise.then链式调用

    let a = new Promise((resolve,reject)=>{ resolve(1) }).then((r)=>{console.log(r)}).then(()=> ...

  4. self-training and co-training

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

  5. Flutter路由(一)

    第一点:push使用 1.pushNamed——Navigator.of(context).pushNamed('routeName') Navigator.of(context).pushNamed ...

  6. 网格UV展开

    原文链接 UV展开是什么 参数曲面的参数域变量一般用UV字母来表达,比如参数曲面F(u,v).所以一般叫的三维曲面本质上是二维的,它所嵌入的空间是三维的.凡是能通过F(u,v)来表达的曲面都是参数曲面 ...

  7. xshell登陆后脚本

    vbs的写法: Sub Main xsh.Screen.Send "ssh 用户名@服务器地址" xsh.Screen.Send VbCr xsh.Screen.WaitForSt ...

  8. [转帖]Ubuntu 对应内核版本

    带有相应Linux内核版本的Ubuntu版本列表 https://www.helplib.com/ubuntu/article_155943   问题: 是否有带有默认对应的Linux内核版本的Ubu ...

  9. Spring(九)--通知

    Spring之Advice通知 Spring原生的经典模式  实现AOPadvice :通知 前置通知:在目标方法执行之前执行!不能改变方法的执行流程和结果!            实现MethodB ...

  10. 初步学习jquery学习笔记(二)

    jQuery事件 jquery是为事件处理而设计的 什么是事件? 页面对不同访问者的相应叫做事件. 事件处理程序指的是html中发生某些事件所调用的方法 实例: 在元素上移动鼠标 选取单选按钮 点击元 ...