java连接和操作zookeeper 示例代码
时间: 2023-08-24 07:21:18 浏览: 96
好的,以下是一个简单的 Java 连接和操作 Zookeeper 的示例代码:
```java
import org.apache.zookeeper.*;
import java.io.IOException;
public class ZookeeperDemo {
private static final String ZOOKEEPER_ADDRESS = "localhost:2181";
private static final int SESSION_TIMEOUT = 5000;
private static ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
connect();
// 创建节点
createNode("/test", "hello zookeeper");
// 获取节点数据
String data = getNodeData("/test");
System.out.println(data);
// 修改节点数据
setData("/test", "hello world");
// 重新获取节点数据
data = getNodeData("/test");
System.out.println(data);
// 删除节点
deleteNode("/test");
close();
}
private static void connect() throws IOException {
zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("Watch event: " + event.getType());
}
});
}
private static void close() throws InterruptedException {
zooKeeper.close();
}
private static void createNode(String path, String data) throws KeeperException, InterruptedException {
byte[] dataBytes = data.getBytes();
zooKeeper.create(path, dataBytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
private static String getNodeData(String path) throws KeeperException, InterruptedException {
byte[] dataBytes = zooKeeper.getData(path, false, null);
return new String(dataBytes);
}
private static void setData(String path, String data) throws KeeperException, InterruptedException {
byte[] dataBytes = data.getBytes();
zooKeeper.setData(path, dataBytes, -1);
}
private static void deleteNode(String path) throws KeeperException, InterruptedException {
zooKeeper.delete(path, -1);
}
}
```
这个示例代码中,首先通过 `ZooKeeper` 类的构造函数连接 Zookeeper 服务。然后创建、获取、修改和删除节点的操作分别对应 `createNode`、`getNodeData`、`setData` 和 `deleteNode` 函数。最后通过 `close` 函数关闭连接。
需要注意的是,Zookeeper 的节点类型有持久化节点和临时节点。在创建节点时需要指定节点类型,例如 `CreateMode.PERSISTENT` 表示持久化节点。除此之外还需要指定节点的访问控制列表,例如 `ZooDefs.Ids.OPEN_ACL_UNSAFE` 表示不做访问控制限制。
希望这个示例代码可以帮助您了解如何在 Java 中连接和操作 Zookeeper。
阅读全文