想象一条路径“/root/child1/child2/child3”
想象一下,在动物园管理员中,可能存在其中的一部分,比如“/root/child1”
Zookeeper 中没有等效的“mkdir -p”;此外,如果任何一个操作失败,ZooKeeper.multi() 都会失败,因此“make path”无法真正融入多重调用中。此外,您可能有其他一些客户端尝试走相同的路径......
这就是我为创建路径而想出的方法。我想知道是否值得检查某个部分是否存在,以保存 contains() 调用的往返过程。
//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)其他一些客户端可能正在尝试写入相同的路径(并且我们希望避免锁定)。
您可以使用Netflix 策展人 https://github.com/Netflix/curator/wiki使使用 Zookeeper 变得更加简单的库
client.create().withMode(CreateMode.PERSISTENT).forPath("/root/child1/child2/child3", new byte[0]).withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE).creatingParentsIfNeeded();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)