想象一个路径“/root/child1/child2/child3”
想象在 zookeeper 中可能存在其中的一部分,比如“/root/child1”
zookeeper 中没有等效的“mkdir -p”;此外,如果任何一个操作失败,ZooKeeper.multi() 将失败,因此“制作路径”不能真正融入到多重调用中。此外,您可能有其他一些客户端尝试创建相同的路径...
这就是我想出的创建路径的方法。我想知道是否值得检查某个部分是否存在,以节省 exists() 调用的往返行程。
//String[] pathParts new String[] { "root", "child1", "child2", "child3" };
public void savePath(String[] pathParts) {
if (zooKeeper.exists(pathString, false) != null) return;
StringBuilder path = new StringBuilder();
for (String pathElement : pathParts) {
path.append(UNIX_FILE_SEPARATOR).append(pathElement);
String pathString = path.toString();
try {
//bother with the exists call or not?
if (zooKeeper.exists(pathString, false) == null) {
zooKeeper.create(pathString, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} catch (KeeperException e) {
if (e.code() != KeeperException.Code.NODEEXISTS)
throw e;
}
}
}
最有效的方法是什么?假设 a) 您事先不知道已经存在多少路径,并且 b) 其他一些客户端可能正在尝试编写相同的路径(并且我们希望避免锁定)。