When should I use batches and when should I use transactions? Can I embed a transaction in a batch? A batch in a transaction?
1条回答 默认 最新
duandan1995 2015-06-03 20:51关注A batch is a collection of operations that are sent to the server as a single unit for efficiency. It is equivalent to sending the same operations as individual requests from different threads. Requests in a batch may be executed out of order, and it's possible for some operations in a batch to succeed while others fail.
In Go, batches are created with the batcher object
DB.B, and must be passed toDB.Run(). For example:err := db.Run(db.B.Put("a", "1").Put("b", "2"))is equivalent to:
_, err1 := db.Put("a", "1") _, err2 := db.Put("b", "2")A transaction defines a consistent and atomic sequence of operations. Transactions guarantee consistency with respect to all other operations in the system: the results of a transaction cannot be seen unless and until the transaction is committed. Since transactions may need to be retried, transactions are defined by function objects (typically closures) which may be called multiple times.
In Go, transactions are created with the DB.Tx method. The
*client.Txparameter to the closure implements a similar interface toDB; inside the transaction you must perform all your operations on this object instead of the original DB. If your function returns an error, the transaction will be aborted; otherwise it will commit. Here is a transactional version of the previous example (but see below for a more efficient version):err := db.Tx(func(tx *client.Tx) error { err := tx.Put("a", "1") if err != nil { return err } return tx.Put("b", "2") })The previous example waits for the "a" write to complete before starting the "b" write, and then waits for the "b" write to complete before committing the transaction. It is possible to make this more efficient by using batches inside the transaction.
Tx.Bis a batcher object, just likeDB.B. In a transaction, you can run batches with eitherTx.RunorTx.Commit.Tx.Commitwill commit the transaction if and only if all other operations in the batch succeed, and is more efficient than letting the transaction commit automatically when the closure returns. It is a good practice to always make the last operation in a transaction a batch executed byTx.Commit:err := db.Tx(func(tx *client.Tx) error { return tx.Commit(tx.B.Put("a", "1").Put("b", "2")) })本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报