通过ZooKeeper客户端工具或ZooKeeper提供的API,可以创建节点。下面是使用Java API创建节点的示例:
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
public class CreateNodeExample {
public static void main(String[] args) throws Exception {
String host = "localhost:2181";
int sessionTimeout = 3000;
ZooKeeper zooKeeper = new ZooKeeper(host, sessionTimeout, null);
String path = "/myNode";
byte[] data = "Hello, ZooKeeper!".getBytes();
CreateMode mode = CreateMode.PERSISTENT;
zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, mode);
zooKeeper.close();
}
}
在上面的示例中,首先创建了一个ZooKeeper客户端实例,然后指定了要创建的节点路径、节点数据、节点创建模式,最后调用create
方法创建节点。需要注意的是,ZooKeeper节点的路径必须是唯一的,不能重复创建同一个路径的节点。