Zookeeper Zkclient客户端
Zkclient是对Zookeeper的原生API进行了包装,实现了超时重连、Watcher反复注册等功能,它可以实现递归创建,删除节点,但是zkClient不能递归给节点赋值。
主要的api如下:
创建永久节点:
public void createPersistent(String path)
public void createPersistent(String path, Object data)
public void createPersistent(String path, Object data, List<ACL> acl)
创建临时节点:
public void createEphemeral(final String path)
public void createEphemeral(final String path, final Object data)
public void createEphemeral(final String path, final Object data, final List<ACL> acl)
删除节点:
public boolean delete(final String path)
public boolean delete(final String path, final int version)
public boolean deleteRecursive(String path)(递归删除节点,在原生api,如果一个节点存在子节点,那么它将无法直接删除,必须一层层遍历先删除全部子节点,然后才能将目标节点删除)
读取节点:
public List<String> getChildren(String path)
更新数据:
public void writeData(String path, Object object)
public void writeData(final String path, Object datat, final int expectedVersion)
判断节点是否存在:
protected boolean exists(final String path, final boolean watch)
注册监听事件:
ZkClient的subscribeChildChanges方法
ZkClient的subscribeDataChanges方法
下面看一个测试,首先导入包:
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.5.0</version> </dependency> <dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> <version>0.1</version> </dependency>
package com.test.protobuf; import org.I0Itec.zkclient.IZkChildListener; import org.I0Itec.zkclient.IZkDataListener; import org.I0Itec.zkclient.ZkClient; import java.util.List; /** * Created by szekinwin on 2017/7/8. */ public class ZkClientDemo { //zookeeper连接地址 private static final String CONNECT_ADR="172.31.19.222:2181,172.31.19.223:2181,172.31.19.234:2181"; public static void main(String[]args){ //5000,连接超时时间 ZkClient zkClient = new ZkClient(CONNECT_ADR,5000); System.out.println("Connect successfully.."); String path="/testRoot"; //监听节点 subscribeChildChanges 监听当前节点以及子节点增加或者删除 zkClient.subscribeChildChanges(path, new IZkChildListener() { public void handleChildChange(String s, List<String> list) throws Exception { System.out.println("路径:"+s); System.out.println("变更的节点为:"+list); } }); //监听节点 subscribeDataChanges 监听当前节点以及子节点内容的变更 zkClient.subscribeDataChanges(path, new IZkDataListener() { public void handleDataChange(String s, Object o) throws Exception { System.out.println("路径:"+s); System.out.println("变更的内容为:"+o.toString()); } public void handleDataDeleted(String s) throws Exception { System.out.println("路径:"+s); } }); //创建节点 true表示递归创建 zkClient.createPersistent("/testRoot/children",true); //修改节点信息 zkClient.writeData("/testRoot","testRoot"); zkClient.writeData("/testRoot","new testRoot"); //修改子节点信息 zkClient.writeData("/testRoot/children","testRoot children"); //递归删除节点 zkClient.deleteRecursive(path); try { Thread.sleep(50000); } catch (InterruptedException e) { e.printStackTrace(); } } }