在Apache ZooKeeper中,znode(Zookeeper节点)是存储数据的结构。创建znode有两种方法:
要创建一个持久节点,您需要使用ZooKeeper的create()
方法,并设置createMode
参数为Persistent
。以下是一个Java示例:
import org.apache.zookeeper.*;
public class CreatePersistentNode {
private static final String CONNECT = "localhost:2181";
private static final int SESSION_TIMEOUT = 3000;
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper(CONNECT, SESSION_TIMEOUT, event -> {
// 处理事件
});
String path = "/myNode";
byte[] data = "My data".getBytes();
CreateMode createMode = CreateMode.PERSISTENT;
zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
System.out.println("Persistent node created: " + path);
zk.close();
}
}
要创建一个临时节点,您需要使用ZooKeeper的create()
方法,并设置createMode
参数为Ephemeral
。以下是一个Java示例:
import org.apache.zookeeper.*;
public class CreateEphemeralNode {
private static final String CONNECT = "localhost:2181";
private static final int SESSION_TIMEOUT = 3000;
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper(CONNECT, SESSION_TIMEOUT, event -> {
// 处理事件
});
String path = "/myNode";
byte[] data = "My data".getBytes();
CreateMode createMode = CreateMode.EPHEMERAL;
zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
System.out.println("Ephemeral node created: " + path);
// 注意:在会话结束时,临时节点将自动删除。因此,不要关闭ZooKeeper连接。
}
}
这两种方法都可以用于创建znode。持久节点会一直存储在ZooKeeper中,直到手动删除。而临时节点仅在当前会话期间存在,当会话结束时,临时节点将自动删除。