Source File
tx.go
Belonging Package
github.com/redis/go-redis/v9
package redisimport ()// TxFailedErr transaction redis failed.const TxFailedErr = proto.RedisError("redis: transaction failed")// Tx implements Redis transactions as described in// https://redis.io/docs/latest/develop/using-commands/transactions. It's NOT safe for concurrent use// by multiple goroutines, because Exec resets list of watched keys.//// If you don't need WATCH, use Pipeline instead.type Tx struct {baseClientcmdablestatefulCmdable// watchArmed reports whether a WATCH issued through Tx.Watch may still be// active on the connection. It is set on a successful WATCH and cleared once// the watched keys are discarded server-side: on UNWATCH (Tx.Unwatch) and on// EXEC, including an aborted EXEC (the TxPipeline closure). Close uses it to// skip an otherwise redundant UNWATCH round trip.//// Only Tx.Watch, Tx.Unwatch and the TxPipeline EXEC closure maintain this// flag. go-redis never issues a standalone DISCARD (Pipeline.Discard is a// client-side buffer reset, not a server command). Issuing a WATCH directly// via Process bypasses tracking, so Close would not release it and the watch// would leak onto the pooled connection; that is the one case where skipping// UNWATCH is unsafe, and using raw Process for WATCH/EXEC/UNWATCH is therefore// unsupported.//// Tx is not safe for concurrent use (see above), so watchArmed is accessed// only from the goroutine that owns the Tx and needs no synchronization.watchArmed bool}func ( *Client) () *Tx {:= Tx{baseClient: baseClient{opt: .cloneOpt(), // Clone options under optLock to avoid race with initConnconnPool: .baseClient.newStickyConnPool(),hooksMixin: .hooksMixin.clone(),pushProcessor: .pushProcessor, // Copy push processor from parent clientonClose: &onCloseHooks{},// Share the HIMPORT fieldset registry: the sticky pool borrows// connections from the parent client's pool, so fieldsets// prepared on them stay valid after the connections are// returned.himport: .himport,// Carry the shared eviction hook (not csc: a sticky Tx must not serve// cached reads) so close/reinit hooks on a Watch-initialized conn still// evict from the parent cache.cscPoolHook: .cscPoolHook,cscActive: .cscActive,},}.init()return &}func ( *Tx) () {.cmdable = .Process.statefulCmdable = .Process.initHooks(hooks{dial: .baseClient.dial,process: .baseClient.process,pipeline: .baseClient.processPipeline,txPipeline: .baseClient.processTxPipeline,})}func ( *Tx) ( context.Context, Cmder) error {:= .processHook(, ).SetErr()return}// Watch prepares a transaction and marks the keys to be watched// for conditional execution if there are any keys.//// The transaction is automatically closed when fn exits.func ( *Client) ( context.Context, func(*Tx) error, ...string) error {:= .newTx()defer .Close()if len() > 0 {if := .Watch(, ...).Err(); != nil {return}}return ()}// Close closes the transaction, releasing any open resources.func ( *Tx) ( context.Context) error {// UNWATCH is only needed while a WATCH is still active. EXEC discards the// watched keys server-side on both commit and abort, so the common// WATCH/.../EXEC paths leave nothing to release and avoid the extra round// trip.if .watchArmed {_ = .Unwatch().Err()}return .baseClient.Close()}// Watch marks the keys to be watched for conditional execution// of a transaction.func ( *Tx) ( context.Context, ...string) *StatusCmd {:= make([]interface{}, 1+len())[0] = "watch"for , := range {[1+] =}:= NewStatusCmd(, ...)_ = .Process(, )// A successful WATCH leaves keys watched on the connection that Close must// later release with UNWATCH.if .Err() == nil {.watchArmed = true}return}// Unwatch flushes all the previously watched keys for a transaction.func ( *Tx) ( context.Context, ...string) *StatusCmd {:= make([]interface{}, 1+len())[0] = "unwatch"for , := range {[1+] =}:= NewStatusCmd(, ...)_ = .Process(, )// The watched keys have been released, so Close need not UNWATCH again.if .Err() == nil {.watchArmed = false}return}// Pipeline creates a pipeline. Usually it is more convenient to use Pipelined.func ( *Tx) () Pipeliner {:= Pipeline{exec: func( context.Context, []Cmder) error {return .processPipelineHook(, )},}.init()return &}// Pipelined executes commands queued in the fn outside of the transaction.// Use TxPipelined if you need transactional behavior.func ( *Tx) ( context.Context, func(Pipeliner) error) ([]Cmder, error) {return .Pipeline().Pipelined(, )}// TxPipelined executes commands queued in the fn in the transaction.//// When using WATCH, EXEC will execute commands only if the watched keys// were not modified, allowing for a check-and-set mechanism.//// Exec always returns list of commands. If transaction fails// TxFailedErr is returned. Otherwise Exec returns an error of the first// failed command or nil.func ( *Tx) ( context.Context, func(Pipeliner) error) ([]Cmder, error) {return .TxPipeline().Pipelined(, )}// TxPipeline creates a pipeline. Usually it is more convenient to use TxPipelined.func ( *Tx) () Pipeliner {:= Pipeline{exec: func( context.Context, []Cmder) error {= wrapMultiExec(, ):= .processTxPipelineHook(, )// EXEC discards the watched keys server-side, so the watch is// cleared only when EXEC actually ran: a nil error (committed),// TxFailedErr (a watched key changed, EXEC returned nil), or an// EXECABORT error (a queued command was rejected, so EXEC discarded// the transaction). All three release the watched keys. Any other// error may be reported before EXEC executes (for example -LOADING on// the MULTI reply) or on a broken connection, so leave watchArmed set// and let Close send UNWATCH rather than risk leaving a watch on a// pooled connection.if == nil || errors.Is(, TxFailedErr) || IsExecAbortError() {.watchArmed = false}return},}.init()return &}func wrapMultiExec( context.Context, []Cmder) []Cmder {if len() == 0 {panic("not reached")}:= make([]Cmder, len()+2)[0] = NewStatusCmd(, "multi")copy([1:], )[len()-1] = NewSliceCmd(, "exec")return}
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |