目录
Zookeeper实战记录-目录:https://blog.csdn.net/weixin_39565597/article/details/104401912
1、依赖
<!-- 单元测试(可选) -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<!-- 日志(可选) -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<!-- zookeeper核心包 -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.6</version>
</dependency>
2、初始化客户端
// 获取zk客户端
// connectString:集群节点地址
// sessionTimeout:超时时间
// Watcher监听器
String connectString = "node1:2181,node2:2181,node3:2181";
Integer sessionTimeout = 2000;
Zookeeper zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent.toString());
}
});
3、create 创建节点
// 参1:节点名称
// 参2:节点值
// 参3:节点权限为任何人均可以访问
// 参4:节点模式为持久化目录节点
String nodeCreated = zkClient.create("/hello5", "www.baidu.com".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(nodeCreated);
4、get/set 获取/设置节点信息
// 获取节点的数据,开启监听器
byte[] data = zkClient.getData("/hello5", new Watcher() {
// 当setData执行之后,会调用此监听器,类型为NodeDataChanged节点数据变化类型
// 结果:WatchedEvent state:SyncConnected type:NodeDataChanged path:/hello5
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent.toString());
}
}, null);
System.out.println(new String(data)); // 结果:www.baidu.com
// 设置节点新值
// 参1:节点名称
// 参2:节点值
// 参3:版本号
Stat stat = zkClient.setData("/hello5", "com.baidu.com".getBytes(), -1);
System.out.println(stat.toString()); // 结果:47244640258,47244640282,1582087926482,1582089581362,4,0,0,0,9,0,47244640258(此处对应Stat结构体的各个值)
5、查询节点是否存在
// 如果不存在,则stat=null
// 参数2:boolean类型时,使用zk构造的默认监听器,Watch类型时,使用自定义监听器
Stat stat = zkClient.exists("/hello5", false);