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 ...
随机推荐
- 【pentaho】【kettle】【Data Integration】试用
要做数据分析,领导让研究一下kettle. 先占个坑. 这里有个3.0的文档: http://wenku.baidu.com/link?url=hvw_cOBIXLXSGvftkGhXQic3CLC7 ...
- 利用AES算法加密数据
准备工作: 模块安装问题: 首先在python中安装Crypto这个包 但是在安装模块后在使用过程中他会报错 下面是解决方法: pip3 install pycrypto 安装会报错 https:// ...
- Python(并发编程进程)
并发编程 二.多进程 要让Python程序实现多进程(multiprocessing),我们先了解操作系统的相关知识. Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊.普通的函 ...
- IIS 搭建过程
Windows自带iis管理器,也就是这个 <ignore_js_op> 我们可以用它来搭建一个网站,然后在局域网内可随意访问我们的电脑. 1.首先,iis的安装. ...
- MyEclipse安装主题(Color Theme)
前段时间发现同学开发使用IDE界面相当炫酷(Mac版的IntelliJ IDEA),个人也比较喜欢那种风格的界面,想想自己MyEclipse IDE界面简直是屌丝啊~~~~ 今天上CSDN看见一篇介绍 ...
- PHP SPL使用方法和他的威力
什么是SPL,如何使用,他有什么作用,下面我我们就讲讲PHP SPL的用法 SPL,PHP 标准库(Standard PHP Library) ,此从 PHP 5.0 起内置的组件和接口,并且从 PH ...
- POJ3281:Dining(dinic+拆点)
题目链接:http://poj.org/problem?id=3281 PS:刷够网络流了,先这样吧,之后再刷,慢慢补. 题意:有F种食物,D种饮料,N头奶牛,只能吃某种食物和饮料(而且只能吃特定的一 ...
- matlab 保存图片的几种方式
最近在写毕业论文, 需要保存一些高分辨率的图片. 下面介绍几种MATLAB保存图片的 方式. 一. 直接使用MATLAB的保存按键来保存成各种格式的图片 你可以选择保存成各种格式的图片, 实际上对于 ...
- mysql数据库从删库到跑路之mysql:视图、触发器、事务、存储过程、函数
mysql:视图.触发器.事务.存储过程.函数 一.视图 视图是一个虚拟表(非真实存在),其本质是[根据SQL语句获取动态的数据集,并为其命名],用户使用时只需使用[名称]即可获取结果集,可以将该结果 ...
- 2017浙江省赛 D - Let's Chat ZOJ - 3961
地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3961 题目: ACM (ACMers' Chatting Messe ...