执行main()看效果,使用zkCli查看节点内容:
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 使用com.101tec.zkclient工具包,操作zookeeper
*/
public class ZkClinetTest {
// private static String ZK_URL = "192.168.1.45:2181,192.168.1.46:2181,192.168.1.41:2181";//连接zookeeper集群
private static String ZK_URL = "localhost:2181";
private static ZkClient zkClient = null;
private static void getInstance() {
if (null == zkClient) {
zkClient = new ZkClient(ZK_URL, 10000);
}
}
public static void main(String[] args) throws InterruptedException {
getInstance();
String path = "/node";
//创建节点
zkClient.createPersistent(path, "123");
//读取节点的值
Object readData = zkClient.readData(path);
System.out.println(readData.toString());
zkClient.createEphemeral("/ephemeral");//创建临时节点
zkClient.createPersistent("/zkclient/zkclient1-1/zkclient2-1", true);//创建永久节点:添加参数true表示支持递归创建
List<String> children = zkClient.getChildren(path);
System.out.println(children);
boolean delete1 = zkClient.deleteRecursive("/zkclient");
if (delete1) {
System.out.println("递归删除成功!");
}
//watcher
zkClient.subscribeDataChanges(path, new IZkDataListener() {
public void handleDataChange(String s, Object o) throws Exception {
System.out.println("节点名称:" + s + "->节点修改后的值:" + o);
}
public void handleDataDeleted(String s) throws Exception {
}
});
zkClient.subscribeChildChanges(path, new IZkChildListener() {
public void handleChildChange(String s, List<String> list) throws Exception {
System.out.println("节点名称:" + s + "->子节点集合:" + list);
}
});
//修改
zkClient.writeData(path, "我把值修改啦!");
TimeUnit.SECONDS.sleep(2);
//新增子节点
zkClient.createPersistent(path + "/node1", "node1");
TimeUnit.SECONDS.sleep(2);
//修改子节点的值
zkClient.writeData(path + "/node1", "node1的值被修改啦!");
TimeUnit.SECONDS.sleep(2);
//删除
boolean delete = zkClient.deleteRecursive(path);
if (delete) {
System.out.println("删除成功!");
}
TimeUnit.SECONDS.sleep(2);
}
}
zkclient操作zookeeper的代码
最新推荐文章于 2022-03-07 16:19:09 发布