1

ZooKeeper的Apache Curator 库使用了很好的“流利”语法。例如,要修改事务中的多个节点,代码如下所示:

client.inTransaction().
    .setData().forNode(node1Path, data1)
    .and()
    .SetData().forNode(node2Path, data2)
    .and()
    .commit();

这很好用,而且恕我直言,生成非常易读的代码。但是,我有一种情况,我必须在事务中修改一组 ZNode。直到运行时我才知道需要修改多少节点或哪些节点。因此,我认为我不能轻松地使用流利的语法。查看文档,我可以手动管理每个 fluent 方法调用返回的代理对象,但是代码需要显式使用CuratorTransaction, TransactionSetDataBuilder,CuratorTransactionBridge等。这显然是可行的,但代码开始看起来很丑陋。

我没有看到与 Curator 进行交易的非流畅方式。有谁知道是否有一个和/或是否有一种“好”的方式在运行时构建事务?具体来说,给定Map<String, String>从 ZNode 路径到需要在该 ZNode 中结束的数据的映射,您将如何以事务方式设置所有节点?

4

2 回答 2

4

给猫剥皮的一种方法:

CuratorTransaction curatorTransaction = client.inTransaction();

for (Map.Entry<String, String> entry : transactionInfo.entrySet()) {
    curatorTransaction = curatorTransaction
        .setData().forNode(entry.getKey(), entry.getValue()).and();
}

// If there was at least one entry in transactionInfo, and() makes it a CuratorTransactionFinal
if (curatorTransaction instanceof CuratorTransactionFinal) {
    ((CuratorTransactionFinal)curatorTransaction).commit();
}
于 2013-08-12T22:48:50.113 回答
0

我使用馆长进行动物园管理员交易,首先我做一些这样的事情

uratorTransaction.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                            .forPath().and();then I commit it like bfos',but the commit method can't  returned,and the exception in the log file is like this:
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:99)
    at org.apache.zookeeper.ZooKeeper.multiInternal(ZooKeeper.java:932)
    at org.apache.zookeeper.ZooKeeper.multi(ZooKeeper.java:912)
    at org.apache.curator.framework.imps.CuratorTransactionImpl.doOperation(CuratorTransactionImpl.java:159)
    at org.apache.curator.framework.imps.CuratorTransactionImpl.access$200(CuratorTransactionImpl.java:44)
    at org.apache.curator.framework.imps.CuratorTransactionImpl$2.call(CuratorTransactionImpl.java:129)
    at org.apache.curator.framework.imps.CuratorTransactionImpl$2.call(CuratorTransactionImpl.java:125)
    at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:107)
    at org.apache.curator.framework.imps.CuratorTransactionImpl.commit(CuratorTransactionImpl.java:121)
于 2015-01-14T11:17:41.777 回答