zookeeper事物操作,其實只是其multi操作的簡單封裝:
public List<OpResult> multi(Iterable<Op> ops)
基本操作:new Transaction(zk).create(...).setData(...)... .commit();
因為每次返回
this 可以串行操作,最后執行commit(),提交批量事務操作,並返回List<OpResult>結果。
package org.apache.zookeeper; import org.apache.zookeeper.data.ACL; import java.util.ArrayList; import java.util.List; /** * Provides a builder style interface for doing multiple updates. This is * really just a thin layer on top of Zookeeper.multi(). * * @since 3.4.0 * */ public class Transaction { private ZooKeeper zk; private List<Op> ops = new ArrayList<Op>(); protected Transaction(ZooKeeper zk) { this.zk = zk; } public Transaction create(final String path, byte data[], List<ACL> acl, CreateMode createMode) { ops.add(Op.create(path, data, acl, createMode.toFlag())); return this; } public Transaction delete(final String path, int version) { ops.add(Op.delete(path, version)); return this; } public Transaction check(String path, int version) { ops.add(Op.check(path, version)); return this; } public Transaction setData(final String path, byte data[], int version) { ops.add(Op.setData(path, data, version)); return this; } public List<OpResult> commit() throws InterruptedException, KeeperException { return zk.multi(ops); } }