我们在写程序的时候往往假设“网络是可靠的”,这是不可靠的。
因此我们才在上一章节定义了“retryOperation()”方法,当在执行操作的时候,假如遇到了类似于“lossConnection”等异常的时候能够在区分“幂等”和“非幂等”操作的前提下
执行相应的措施。
本节我们将讲解“retryOperation()”方法的第一次应用:创建节点
我们定义“ensureExists()”方法
“ensureExists()”方法的访问权限是“protected”,返回时“void”,参数有:
path //节点路径
data //节点数据
acl //节点权限策略
createMode //节点类型
protected void ensureExists(final String path, final byte[] data,
final List<ACL> acl, final CreateMode flags) {
try {
retryOperation(new ZooKeeperOperation() {
public boolean execute() throws KeeperException, InterruptedException {
Stat stat = zookeeper.exists(path, false);
if (stat != null) {
return true;
}
zookeeper.create(path, data, acl, flags);
return true;
}
});
} catch (KeeperException e) {
LOG.warn("Caught: " + e, e);
} catch (InterruptedException e) {
LOG.warn("Caught: " + e, e);
}
}
这个方法捕捉了两个异常:KeeperException和InterruptedException