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.Tx
parameter 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.B
is a batcher object, just likeDB.B
. In a transaction, you can run batches with eitherTx.Run
orTx.Commit
.Tx.Commit
will 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")) })
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 VB.NET2022如何生成发布成exe文件
- ¥30 matlab appdesigner私有函数嵌套整合
- ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
- ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
- ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
- ¥15 关于freesurfer使用freeview可视化的问题
- ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
- ¥15 求SC-LIWC词典!
- ¥20 有关esp8266连接阿里云
- ¥15 C# 调用Bartender打印机打印