zookeeper事务

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);
    }
}

 

posted @ 2016-11-29 14:39  WindWant  阅读(3335)  评论(0编辑  收藏  举报
文章精选列表