本文使用java操作zookeeper都是在集群环境下进行的
搭建集群文章
org.apache.logging.log4j
log4j-core
2.8.2
org.apache.zookeeper
zookeeper
3.6.0
junit
junit
4.12
一定要仔细比对集群的ip
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class TestZk {
// 集群ip
private String connectString = "192.168.77.128,192.168.77.129,192.168.77.130";
// session超时时间 60s
private Integer sessionTimeout = 60 * 1000;
ZooKeeper zkClient;
// 连接集群
@Before
public void init() throws IOException {
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {// 监听器
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("监听到了");
}
});
}
}
出现绿色说明连接成功了
@Before
public void init() throws IOException{
// 省略...
}
// 创建节点
@Test
public void createNode() throws InterruptedException, KeeperException {
String node = zkClient.create(
"/look",
"你好Look".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
// 参数1:要创建的节点的路径
// 参数2:节点数据
// 参数3:节点权限
// 参数4:节点的类型
System.out.println("node = " + node);
}
// 获取节点值
@Test
public void getNodeData() throws InterruptedException, KeeperException {
byte[] clientData = zkClient.getData("/look", false, new Stat());
System.out.println("clientData = " + new String(clientData));
}
// 修改节点值
@Test
public void updateNodeData() throws InterruptedException, KeeperException {
Stat stat = zkClient.setData("/look", "你好 架构师".getBytes(), 0);
System.out.println("stat = " + stat);
}
// 删除节点
@Test
public void deleteNodeData() throws InterruptedException, KeeperException {
zkClient.delete("/look", 1);
System.out.println("删除成功!");
}
获取子节点 // 获取子节点
@Test
public void getChildren() throws InterruptedException, KeeperException {
List children = zkClient.getChildren("/china", false);// false:不监听
children.forEach(System.out::println);
}
// 监听子节点的变化
@Test
public void getChildren1() throws Exception {
List children = zkClient.getChildren("/", true);// true:注册监听
children.forEach(System.out::println);
// 让线程不停止,等待监听的响应
System.in.read();
}
// 判断Znode是否存在
@Test
public void exist() throws Exception {
Stat stat = zkClient.exists("/look-word", false);
System.out.println(stat == null ? "不存在" : "存在");
}
原文链接:https://www.cnblogs.com/look-word/p/16488652.html
留言与评论(共有 0 条评论) “” |