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 ...
随机推荐
- SpringCloud 进阶之Ribbon和Feign(负载均衡)
1. Ribbon 负载均衡 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端,负载均衡的工具; 1.1 Ribbon 配置初步 1.1.1 修改 micros ...
- Seek the Name, Seek the Fame---poj2752(kmp中的Next数组)
题目链接:http://poj.org/problem?id=2752 题意就是求出是已知s串的前缀的长度x,并且要求此前缀也是s串的后缀:求出所有的 x : Next[i]的含义是前i个元素的前缀和 ...
- 内核通信之Netlink源码分析-基础架构
2017-07-04 netlink是一种基于网络的通信机制,一般用于内核内部或者内核与用户层之间的通信.其有一个明显的特点就是异步性,通信的双方不要求同时在线,也就不用阻塞等待.NetLink按照数 ...
- centos7手动编译安装Libvirt常见问题
由于功能需要,体验了手动编译安装Libvrt,还是碰到了不少问题,这里总结如下仅限于centos7: 1.configure: error: You must install the pciacces ...
- redis之持久化操作
简介 Redis是一种高级key-value数据库.它跟memcached类似,不过数据可以持久化,而且支持的数据类型很丰富.有字符串,链表,集 合和有序集合.支持在服务器端计算集合的并,交和补集(d ...
- hibernate 单向 n-n
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/qilixiang012/article/details/27956057 域模型: 关系数据模型 n ...
- React:快速上手(7)——使用中间件实现异步操作
React:快速上手(7)——使用中间件实现异步操作 本文参考链接:Stack Overflow redux-thunk 我们使用store.dispath进行派发时,只能传递一个普通对象进去,如下: ...
- ruby中的可调用对象--proc和lamdba
ruby中将块转变成对象的三种方法 ruby中的大部分东西都是对象,但是块不是.那么,如果你想存下来一个块,方便以后使用,你就需要一个对象.ruby中有三种方法,把块转换成可以利用的对象. Proc. ...
- tensorflowxun训练自己的数据集之从tfrecords读取数据
当训练数据量较小时,采用直接读取文件的方式,当训练数据量非常大时,直接读取文件的方式太耗内存,这时应采用高效的读取方法,读取tfrecords文件,这其实是一种二进制文件.tensorflow为其内置 ...
- python3_Logging模块详解
python的logging模块提供了通用的日志系统,可以方便第三方模块或应用使用. 简单使用 import logging # logging.config.fileConfig("./l ...