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. leetcode 34在排序数组中查找元素的第一个和最后一个位置

    class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { ve ...

  2. Pycharm 常用快捷键-Windows版

    常用快捷键: Ctrl + / 行注释(可选中多行) Ctrl + Alt + L 代码格式化 Tab / Shift + Tab 缩进.不缩进当前行(可选中多行) Ctrl + D 复制选定的区域 ...

  3. [Python]if语句的练习

    习题: 小明身高1.75,体重80.5kg.请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:低于18.5:过轻 18.5-25:正常 25-28:过重 28-32:肥 ...

  4. 63不同路径II

    题目: 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” ).机器人每次只能向下或者向右移动一步.机器人试图达到网格的右下角(在下图中标记为“Finish”).现在考 ...

  5. cocos2dx基础篇(22) 基本动画CCAnimation/CCAnimate

    [小知识] CCSpriteFrame     :精灵帧.    它是相对动画而产生的,其实就是一张纹理图片. CCAnimationFrame  :动画帧.    由精灵帧与间隔帧数组成,是动画CC ...

  6. python学习之生成器

    4.6 生成器Generrator ​ 生成器本质就是迭代器.python社区生成器与迭代器是一种. ​ 生成器与迭代器的唯一区别:生成器是我们自己用python代码构建的 4.6.1生成器初识 py ...

  7. 【神经网络与深度学习】CIFAR-10数据集介绍

    CIFAR-10数据集含有6万个32*32的彩色图像,共分为10种类型,由 Alex Krizhevsky, Vinod Nair和 Geoffrey Hinton收集而来.包含50000张训练图片, ...

  8. lambda得用法

  9. 深度解析Maven

    此文来源于: https://www.cnblogs.com/hafiz/p/8119964.html 带你深度解析Maven   一.What`s Maven? Maven是基于项目对象模型(POM ...

  10. JavaScript中:地址引用的特性,导致静态初始值被修改

    问题分类 JavaScript,值引用,地址引用 问题描述 开发过程中,服务端将静态配置数据从mysql数据库中读取到内存中,方便调用. 在实现流派功能时,需从数据库中读取流派种类数据到内存中,由于其 ...