07_ZkClient提供的API使用
1. ZkClient API简介
zkclient是Github上一个开源的ZooKeeper客户端,在原生ZooKeeper API接口上进行包装,同时在内部实现了session超时重连,Watcher反复注册等功能
2. Maven工程方式导入ZkClient API
通过POM.xml方式,指定依赖的zookeepr包以及zkclient包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.newforce</groupId>
<artifactId>testzkclient</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.5</version>
</dependency>
</dependencies> </project>
3. ZkClient API使用
3.1 create session 创建和zookeeper集群间的连接
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer; /**
* ZkClient library usage
*/
public class CreateSession {
public static void main(String args[]){
ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new SerializableSerializer());
System.out.println("Connection OK!"); }
}
核心代码分析:
1)和zookeeper原生API不同,通过zkclient API创建会话,需要提供session timout, connection timeout两个定时器
2)同时要提供1个序列化器实例,原因在于后续创建znode节点时,写入的数据(java对象)会自动通过序列化器来转换为byte[]
3)同理,读取出的byte[]的数据,也会自动通过序列化器直接转换为Java对象
3.2 创建znode节点
/**
* ZkClient library usage
*/
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
public class CreateNode { public static void main(String args[]){ ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new SerializableSerializer());
User u = new User();
String actual_path = zc.create("/node_zkclient", u, CreateMode.PERSISTENT); //直接将实例u写入,自动通过序列化为byte[]
System.out.println("Create path is: " + actual_path);
} private class User{
private Integer id;
private String name; public Integer getId(){
return this.id;
}
public String getName(){
return this.name;
}
public String getInfo(){
return this.name + this.id;
}
}//User
}
3.3 修改节点数据
/**
* ZkClient library usage
*/
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode; public class SetData {
public static void main(String args[]){
ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new SerializableSerializer()); User u = new User();
u.setId(1);
u.setName("shayzhang"); String actual_path = zc.create("/node_zkclient", u, CreateMode.PERSISTENT); u.setId(2);
u.setName("zhangjin");
zc.writeData(actual_path, u); //直接写入实例,自动通过连接创建时创建的序列化实例,转换为byte[] }
}
3.4 获取节点数据
/**
* ZkClient library usage
*/
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat; public class GetData {
public static void main(String args[]){
ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new SerializableSerializer());
User u = new User();
u.setId(1);
u.setName("shayzhang"); String actual_path = zc.create("/node_zkclient", u, CreateMode.PERSISTENT);
System.out.println("Create path is: " + actual_path); Stat stat = new Stat();
u = zc.readData(actual_path, stat); if (u == null){
System.out.println("Node doesn't exist!");
}else{
System.out.println(u.getInfo());
System.out.println(stat);
}
}
}
3.5 获取子节点列表
/**
* ZkClient library usage
*/
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import java.util.List; public class GetChildren {
public static void main(String args[]){
ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new SerializableSerializer()); User u = new User();
u.setId(1);
u.setName("shayzhang"); String actual_path = zc.create("/node_zkclient", u, CreateMode.PERSISTENT);
System.out.println("Create path is: " + actual_path);
List<String> children_list = zc.getChildren(actual_path);
System.out.println("Children list of /node_zkclient is : " + children_list.toString()); //打印子节点列表 }
}
3.6 删除节点
/**
* ZkClient library usage
*/
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer; public class DeleteNode {
public static void main(String args[]){
ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new SerializableSerializer()); String delete_node = "/node_zkclient"; //delete node without children
boolean e1 = zc.delete(delete_node);
System.out.println("Delete node without children: " + e1); // delete node and all children
boolean e2 = zc.deleteRecursive(delete_node);
System.out.println("Delete node and children: " + e2); }
}
3.7 判断节点是否存在
/**
* ZkClient library usage
*/
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer; public class NodeExist {
public static void main(String args[]){
ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new SerializableSerializer());
String check_node = "/node_zkclient";
boolean exist = zc.exists(check_node);
System.out.println("Node exist status is: " + exist); }
}
3.8 订阅子节点列表发生变化
/**
* ZkClient library usage
*/
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import java.util.List; public class SubscribeChildren {
public static void main(String args[]){
ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new SerializableSerializer());
System.out.println("Connected to zk server!"); // subscribe children change event, multiple subscribe
List<String> results = zc.subscribeChildChanges("/node_zkclient", new ZkChildListener()); // sleep until receive event notify
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
} }//main private static class ZkChildListener implements IZkChildListener{
public void handleChildChange(String s, List<String> list) throws Exception {
//print parent path
System.out.println("Parent path: " + s);
//print current children
System.out.println("Current children: " + list.toString());
}
}//ZkChildListener
}
3.9 订阅数据变化
/**
* ZkClient library usage
*/
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.BytesPushThroughSerializer; public class SubscribeData {
public static void main(String args[]){
//使用了新的序列化器, zk命令行写入的数据才能被检测
ZkClient zc = new ZkClient("192.168.179.101:2181", 5000, 5000, new BytesPushThroughSerializer()); //写入什么直接当做byte[]进行存储
System.out.println("Connected to zk server!"); // subscribe data change event, multiple subscribe
zc.subscribeDataChanges("/node_zkclient", new ZkDataListener()); // sleep until receive event notify
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
} } private static class ZkDataListener implements IZkDataListener{
public void handleDataChange(String s, Object o) throws Exception { //覆写方法1
System.out.println("Path Data Changed: " + s);
System.out.println("Current Data: " + o.toString());
}
public void handleDataDeleted(String s) throws Exception { //覆写方法2
System.out.println("Data Deleted: " + s);
}
}//ZkDataListener
}
07_ZkClient提供的API使用的更多相关文章
- 微软提供的API的各个版本之间的区别
First Floor Software这个diff lists非常方便的给出了微软提供的API的各个版本之间的区别,比如下表是.NET 4和.NET 4.5的API变化总结.我们可以看到.NET 4 ...
- Android 系统api实现定位及使用百度提供的api来实现定位
目前在国内使用定位的方法主要是 1. Android系统提供的 LocationManager locationManager = (LocationManager) getSystemService ...
- 返璞归真 asp.net mvc (11) - asp.net mvc 4.0 新特性之自宿主 Web API, 在 WebForm 中提供 Web API, 通过 Web API 上传文件, .net 4.5 带来的更方便的异步操作
原文:返璞归真 asp.net mvc (11) - asp.net mvc 4.0 新特性之自宿主 Web API, 在 WebForm 中提供 Web API, 通过 Web API 上传文件, ...
- [转]在static代码块或static变量的初始化过程中使用ServiceManager提供的api的陷阱
一. 案例 1.源码: /** @hide */ private TelephonyManager(int slotId) { mContext = null; mSlotId = slotId; i ...
- 如何调用别人提供的API?
1:一般使用聚合数据提供的API: 百度聚合数据,进入: 2:一般是有用户名的直接登录,没有用户名的先进行注册.在搜索框中输入你想查找的API方面的关键字:例如:有关健康的 点开任意一个,你将会看到: ...
- Django FBV CBV以及使用django提供的API接口
FBV 和 CBV 使用哪一种方式都可以,根据自己的情况进行选择 看看FBV的代码 URL的写法: from django.conf.urls import url from api import v ...
- 【转】根据中国气象局提供的API接口实现天气查询
本文转载自 老三 的 三叶草 中国气象局提供了三个天气查询的API接口: [1]http://www.weather.com.cn/data/sk/101190101.html [2]http://w ...
- 根据中国气象局提供的API接口实现天气查询
中国气象局提供了三个天气查询的API接口: [1]http://www.weather.com.cn/data/sk/101190101.html [2]http://www.weather.com. ...
- 使用servlet3.0提供的API来进行文件的上传操作
servlet 3.0针对文件上传做了一些优化,提供了一些更加人性化的API可以直接在request中的到文件的名称.文件size,MIME类型,以及用InputStream表示的文件流的信息 @Re ...
随机推荐
- 解决启动Tomcat时遇到INFO: Destroying ProtocolHandler ["ajp-apr-8009"]
问题描述: 启动Tomcat时,出现INFO: Destroying ProtocolHandler ["ajp-apr-8009"]等信息 这说明端口号被占用了... 解决方法: ...
- Hadoop的Combiner
在很多MapReduce应用的场景中,假设能在向reducer分发mapper结果之前做一下"本地化Reduce".一wordcount为样例,假设作业处理中的文件单词中" ...
- VMware 虚拟机 Ubuntu 不能全屏问题
在刚安装完ubuntu后,屏幕不能全屏显示,此时: 1.安装VMware Tools 步骤: 1.1 进入ubuntu系统后,点击虚拟机上的[虚拟机]->[安装 vmware tools ...
- vim 设置字体和解决乱码
在 C:\Program Files (x86)\Vim 目录中的 _vimrc 文件中加入下面两行 set fileencodings=utf-8,gb2312,gb18030,gbk,ucs-bo ...
- Installshield 宏定义控制版本
定义宏 在Build =>Setting => 以空格为准定义宏 使用宏 在方法里 #if 宏名称 代码 #else 代码 #endif
- Linux下修改.bash_profile 文件改变PATH变量的值
Linux中含有两个重要的文件 /etc/profile和$HOME/.bash_profile 每当系统登陆时都要读取这两个文件,用来初始化系统所用到的变量,其中/etc/profile是超级用户所 ...
- Spark的集群管理器
上篇文章谈到Driver节点和Executor节点,但是如果想要运行Driver节点和Executor节点,就不能不说spark的集群管理器.spark的集群管理器大致有三种,一种是自带的standa ...
- tcp五层模型
物理层由来:上面提到,孤立的计算机之间要想一起玩,就必须接入internet,言外之意就是计算机之间必须完成组网 物理层功能:主要是基于电器特性发送高低电压(电信号),高电压对应数字1,低电压对应数字 ...
- Element 中表单非必填数据项 必须为数字的验证问题
Element-ui 的el-form组建中,自带基本的验证功能,比如某些项必填的验证,直接加入rules 规则中即可,如下实例: 在页面中书写如下: <el-form-item label=& ...
- sidekiq-cron定时任务
参考 时间格式 gem "sidekiq-cron", "~> 1.1" route.rb下添加 require 'sidekiq/cron/web', ...