想象一下路径"/ root/child1/child2/child3"
想象一下,在zookeeper中,可能存在其中一部分,比如"/ root/child1"
在zookeeper中没有"mkdir -p"的等价物; 此外,如果任何一个操作失败,ZooKeeper.multi()将失败,因此"make path"无法真正融入多次调用.此外,你可以让其他一些客户尝试制作相同的路径......
这就是我为创建路径而想出的.我想知道是否值得检查一个部件是否存在,以保存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;
}
}
} …Run Code Online (Sandbox Code Playgroud) 假设我想把这棵树写成动物园管理员
. a
. / \
. b c
. / \
. d e
Run Code Online (Sandbox Code Playgroud)
一些其他客户端可以在创建它之后立即删除节点b,但在我能够写入节点"d"或"e"之前.
有没有办法可以原子地编写这个层次结构,或者可能锁定某个路径?