Zookeeper客户端使用(使用原生zookeeper)
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)的更多相关文章
- Zookeeper系列三:Zookeeper客户端的使用(Zookeeper原生API如何进行调用、ZKClient、Curator)和Zookeeper会话
一.Zookeeper原生API如何进行调用 准备工作: 首先在新建一个maven项目ZK-Demo,然后在pom.xml里面引入zk的依赖 <dependency> <groupI ...
- ZooKeeper客户端原生API的使用以及ZkClient第三方API的使用
这两部分内容的介绍主要讲的是节点及节点内容和子节点的操作,并且讲解的节点的事件监听以及ACL授权 ZooKeeper客户端原生API的使用 百度网盘地址: http://pan.baidu.com/s ...
- Zookeeper客户端使用(使用Curator)
Zookeeper客户端(使用Curator) 三.使用curator客户端 在pom.xml中加入依赖 <dependency> <groupId>org.apache.cu ...
- Zookeeper客户端使用(使用zkclient)
Zookeeper客户端使用 二.使用zkclient 在pom.xml中加入依赖 <dependency> <groupId>com.101tec</groupId&g ...
- zookeeper客户端使用原生JavaApi操作节点
1.引入依赖 <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zook ...
- Zookeeper客户端Curator基本API
在使用zookeper的时候一般不使用原生的API,Curator,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连.反复注册Watcher和NodeExistsExceptio ...
- Zookeeper客户端Curator的使用,简单高效
Curator是Netflix公司开源的一个Zookeeper客户端,与Zookeeper提供的原生客户端相比,Curator的抽象层次更高,简化了Zookeeper客户端的开发量. 1.引入依赖: ...
- Zookeeper客户端Curator使用详解
Zookeeper客户端Curator使用详解 前提 最近刚好用到了zookeeper,做了一个基于SpringBoot.Curator.Bootstrap写了一个可视化的Web应用: zookeep ...
- 7.5 zookeeper客户端curator的基本使用 + zkui
使用zookeeper原生API实现一些复杂的东西比较麻烦.所以,出现了两款比较好的开源客户端,对zookeeper的原生API进行了包装:zkClient和curator.后者是Netflix出版的 ...
随机推荐
- Viola-Jones(人脸检测)
Viola-Jones 人脸检测 1.Haar特征抽取 ‘ 2. Adaboost 算法
- tf工程化部署相关
1.TensorFlow 模型保存/载入的两种方法 https://blog.csdn.net/thriving_fcl/article/details/71423039 [讲解清晰,2种方法都有缺陷 ...
- Mysql数据库事务的四大特性:
什么是事务? 事务Transaction,是指作为一个基本工作单元执行的一系列SQL语句的操作,要么完全地执行,要么完全地都不执行.为什么要使用事务:保证对数据操作的完整性和准确性.1,原子性:一个事 ...
- LeetCode.993-二叉树中的堂兄弟(Cousins in Binary Tree)
这是悦乐书的第374次更新,第401篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第235题(顺位题号是993).在二叉树中,根节点在深度0处,并且每个深度为k的节点的子 ...
- upd通讯Recvfrom设置阻塞不起作用
把自己踩到的坑记录一下,在做UDP通讯的时候,发现自己的程序没有收数据居然也有百分之十二的cpu占用率,通过性能分析工具了解到时recvfrom函数一直在执行,虽然设置阻塞并且确认成功了, ;//阻塞 ...
- switch-case的选择用法
企业发放的奖金根据利润提成.利润I低于或等于100000元的,奖金可提0.1:利润高于100000元,低于200000(100000<I<=200000)时,低于100000元的部分按10 ...
- Mysql 字段类型与查询类型不一致导致索引使用失败
今天优化数据库的慢查询,有一条Sql让我百思不得其jie,就是他了. SELECT * FROM test WHERE user_id=1; 用explain 去分析一下 索引都有了,为什么还要扫描全 ...
- vue,基于element的tree组件封装
封装组件代码 // 组件:树 /* 参数说明-属性: 1.treeData:展示数据(array) 2.treeEmptyText:内容为空的时候展示的文本(String) 3.treeNodeKey ...
- 小记---------Elasticsear搭建
Elasticsear搭建 创建用户: useradd elasticsearch passwd elasticsearch 1.解压 tar -zxvf elasticsearch-5.5.2. ...
- Nmap 在 WSL 中工作不正常
Problem binding to interface , errno: 92 socket_bindtodevice: Protocol not available Problem binding ...