核心代码如下:
package com.zsj.zkclient.test;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
public class ZkClientBase {
static final String CONNECT_ADDR = "localhost:2181";
static final int SESSION_TIMEOUT = 5000;
static ZkClient zkClient = new ZkClient(new ZkConnection(CONNECT_ADDR), SESSION_TIMEOUT, new CustomSerializer());
public static void main(String[] args) throws InterruptedException {
// 3.更新和判断节点是否存在
zkClient.createPersistent("/super/c2", true);
zkClient.createPersistent("/super/c2/xxf", true);
zkClient.createPersistent("/super/c2/xxf/xds", true);
zkClient.createPersistent("/super/c2/xxf/sss", true);
zkClient.createPersistent("/super/c2/xxf/xds/sdfs", true);
zkClient.createPersistent("/super", true);
zkClient.writeData("/super/c1", "新内ssss容452werf6"); // 修改指定节点的值
printChilds("/super");
addListener("/super");
zkClient.writeData("/super/c1", "新qqq52werf6"); // 修改指定节点的值
new Thread(()->{
while(true){
// printConfigs();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();;
TimeUnit.HOURS.sleep(5);
zkClient.close();
}
static Map<String, String> configs = new HashMap<String, String>();
static void printConfigs() {
for (String key : configs.keySet()) {
System.out.format("map--->node=%s,data=%s \n", key, configs.get(key));
}
}
static void printChilds(String path) {
List<String> childs = zkClient.getChildren(path);
for (String child : childs) {
String childPath = path + "/" + child;
if (zkClient.countChildren(childPath) > 0) {
printChilds(childPath);
}
String cData = zkClient.readData(childPath);
configs.put(childPath, cData);
System.out.format("node=%s,data=%s \n", childPath, cData);
}
}
static void addListener(String path) {
List<String> childs = zkClient.getChildren(path);
for (String child : childs) {
final String childPath = path + "/" + child;
if (zkClient.countChildren(childPath) > 0) {
addListener(childPath);
}
subscribe(childPath);
}
}
private static void subscribe(final String childPath) {
System.out.println("subscribeDataChanges-->" + childPath);
zkClient.subscribeDataChanges(childPath, new IZkDataListener() {
public void handleDataDeleted(String s) throws Exception {
System.out.println("删除的节点为:" + s);
configs.remove(s);
}
public void handleDataChange(String s, Object o) throws Exception {
System.out.println("变更节点为:" + s + ",变更数据为:" + o);
if (o == null) {
configs.remove(s);
return;
}
configs.put(s, o.toString());
}
});
zkClient.subscribeChildChanges(childPath, new IZkChildListener() {
public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
if(currentChilds==null) {
return ;
}
for(String cd:currentChilds) {
subscribe(parentPath+"/"+cd);//重新订阅
}
}
});
}
}
class CustomSerializer implements ZkSerializer {
/** default utf 8 */
private String charset = "UTF-8";
public CustomSerializer() {
}
public CustomSerializer(String charset) {
this.charset = charset;
}
public byte[] serialize(Object data) throws ZkMarshallingError {
try {
byte[] bytes = String.valueOf(data).getBytes(charset);
return bytes;
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError("Wrong Charset:" + charset);
}
}
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
String result = null;
try {
result = new String(bytes, charset);
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError("Wrong Charset:" + charset);
}
return result;
}
}
<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.zsj.zkclient</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
</dependencies>
</project>
运行效果如下:
变更节点为:/super/c2/xxf/sassaa/saassaas/assaas/aaa/assaa,变更数据为:assaasasas
parentPath: /super/c2/xxf/sassaa/saassaas/assaas/aaa/assaa
currentChilds: null
删除的节点为:/super/c2/xxf/sassaa/saassaas/assaas/aaa/assaa
parentPath: /super/c2/xxf/sassaa/saassaas/assaas/aaa
currentChilds: []