通過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節點的路徑必須是唯一的,不能重復創建同一個路徑的節點。