基于curator framework zk工具使用
1.添加依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.8</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.12.0</version>
</dependency>
自己封装工具类
package com.wang.zookeeper.util;
import com.google.common.base.Stopwatch;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.transaction.CuratorTransaction;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class ZKClient {
private CuratorFramework client = null;
public ZKClient(String connectionInfo) {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.newClient(connectionInfo, retryPolicy);
client.start();
}
public boolean crateNode(String path, CreateMode createMode, String data) {
try {
client.create().withMode(createMode).forPath(path, data.getBytes());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean deleteNode(String path) {
try {
client.delete().forPath(path);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean deleteChildrenIfNeededNode(String path) {
try {
client.delete().deletingChildrenIfNeeded().forPath(path);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean isExistNode(String path) {
try {
Stat stat = client.checkExists().forPath(path);
return stat != null ? true : false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public int isPersistentNode(String path) {
try {
Stat stat = client.checkExists().forPath(path);
if (stat == null) {
return 2;
}
if (stat.getEphemeralOwner() > 0) {
return 1;
}
return 0;
} catch (Exception e) {
e.printStackTrace();
return 2;
}
}
public String getNodeData(String path) {
try {
byte[] bytes = client.getData().forPath(path);
return new String(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean registerWatcherNodeChanged(String path, NodeCacheListener nodeCacheListener) {
NodeCache nodeCache = new NodeCache(client, path, false);
try {
nodeCache.getListenable().addListener(nodeCacheListener);
nodeCache.start(true);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean registerWatcherAllNodeChanged(String path, TreeCacheListener treeCacheListener) {
TreeCache treeCache = new TreeCache(client, path);
try {
treeCache.start();
treeCache.getListenable().addListener(treeCacheListener);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean updateNodeData(String path, String newValue) {
if (!isExistNode(path)) {
return false;
}
try {
client.setData().forPath(path, newValue.getBytes());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public CuratorTransaction startTransaction() {
return client.inTransaction();
}
}
main方法测试
节点增删改查,并且监听节点下所有事件
public static void main(String[] args) throws InterruptedException {
String url = "127.0.0.1:2181";
Stopwatch stopwatch = Stopwatch.createStarted();
ZKClient zkClient = new ZKClient(url);
stopwatch.stop();
System.out.println("zk连接成功,耗时:" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "毫秒");
boolean root = zkClient.isExistNode("/");
System.out.println("节点/是否存在:" + root);
boolean existNode = zkClient.isExistNode("/dubbo");
System.out.println("节点/dubbo是否存在:" + existNode);
if (existNode) {
} else {
boolean crateNode = zkClient.crateNode("/dubbo", CreateMode.PERSISTENT, "我是天地");
System.out.println("节点/dubbo是否创建成功:" + crateNode);
}
zkClient.registerWatcherAllNodeChanged("/dubbo", (curatorFramework, treeCacheEvent) -> {
System.out.println("=======节点:" + treeCacheEvent.getType() + "发生变化=======");
ChildData childData = treeCacheEvent.getData();
switch (treeCacheEvent.getType()) {
case NODE_ADDED:
System.out.println("/dubbo节点,新增节点:" + childData.getPath() + ",节点内容:" + new String(childData.getData()));
break;
case NODE_REMOVED:
System.out.println("/dubbo节点,删除节点:" + childData.getPath() + ",节点内容:" + new String(childData.getData()));
break;
case NODE_UPDATED:
System.out.println("/dubbo节点,修改节点:" + childData.getPath() + ",节点内容:" + new String(childData.getData()));
break;
default:
System.out.println("当前事件:" + treeCacheEvent.getType() + ",非节点变动事件,不做处理");
break;
}
});
String data = zkClient.getNodeData("/dubbo");
System.out.println("节点/dubbo获取内容:" + data);
boolean existCbdNode = zkClient.isExistNode("/dubbo/cbd");
System.out.println("节点/dubbo/cbd是否存在:" + existCbdNode);
if (!existCbdNode) {
boolean crateCbdNode = zkClient.crateNode("/dubbo/cbd", CreateMode.PERSISTENT, "我是cbd");
System.out.println("节点/dubbo是否创建成功:" + crateCbdNode);
}
String cbdata = zkClient.getNodeData("/dubbo/cbd");
System.out.println("节点/dubbo/cbd获取内容:" + cbdata);
new CountDownLatch(1).await();
}
上面监听状态下。另外服务更新节点
public static void main(String[] args) {
String url = "127.0.0.1:2181";
Stopwatch stopwatch = Stopwatch.createStarted();
ZKClient zkClient = new ZKClient(url);
stopwatch.stop();
System.out.println("zk连接成功,耗时:" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "毫秒");
String path = "/dubbo/sss";
boolean existCbdNode = zkClient.isExistNode(path);
System.out.println("节点/dubbo/sss是否存在:" + existCbdNode);
if (!existCbdNode) {
boolean crateCbdNode = zkClient.crateNode(path, CreateMode.PERSISTENT, "我是sss");
System.out.println("节点/dubbo/sss是否创建成功:" + crateCbdNode);
} else {
boolean updateCbdNode = zkClient.updateNodeData(path, "我是变更后的sss");
System.out.println("节点/dubbo/sss是否更新成功:" + updateCbdNode);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
zkClient.deleteNode(path);
}
}