redis/pipeline.go

111 lines
2.0 KiB
Go
Raw Normal View History

package redis
2015-11-04 15:25:48 +03:00
import (
"sync"
"gopkg.in/redis.v5/internal"
2016-10-09 13:49:28 +03:00
"gopkg.in/redis.v5/internal/pool"
2015-11-04 15:25:48 +03:00
)
2015-06-04 11:50:24 +03:00
// Pipeline implements pipelining as described in
2015-11-04 15:25:48 +03:00
// http://redis.io/topics/pipelining. It's safe for concurrent use
2015-09-12 09:36:03 +03:00
// by multiple goroutines.
2014-05-11 11:42:40 +04:00
type Pipeline struct {
cmdable
statefulCmdable
2014-05-11 11:42:40 +04:00
exec func([]Cmder) error
2015-06-04 11:50:24 +03:00
2016-10-13 12:11:58 +03:00
mu sync.Mutex
cmds []Cmder
closed bool
}
func (c *Pipeline) Process(cmd Cmder) error {
c.mu.Lock()
c.cmds = append(c.cmds, cmd)
c.mu.Unlock()
2016-06-17 15:09:38 +03:00
return nil
2015-01-24 15:12:48 +03:00
}
2015-09-12 09:36:03 +03:00
// Close closes the pipeline, releasing any open resources.
func (c *Pipeline) Close() error {
2016-10-13 12:11:58 +03:00
c.mu.Lock()
c.discard()
c.closed = true
c.mu.Unlock()
return nil
}
2015-06-04 11:50:24 +03:00
// Discard resets the pipeline and discards queued commands.
func (c *Pipeline) Discard() error {
c.mu.Lock()
2016-10-13 12:11:58 +03:00
err := c.discard()
c.mu.Unlock()
return err
}
func (c *Pipeline) discard() error {
if c.closed {
return pool.ErrClosed
2014-05-11 11:42:40 +04:00
}
c.cmds = c.cmds[:0]
2014-05-11 11:42:40 +04:00
return nil
2012-08-20 00:19:00 +04:00
}
2015-11-04 15:25:48 +03:00
// Exec executes all previously queued commands using one
// client-server roundtrip.
//
2014-05-11 11:42:40 +04:00
// Exec always returns list of commands and error of the first failed
// command if any.
func (c *Pipeline) Exec() ([]Cmder, error) {
defer c.mu.Unlock()
c.mu.Lock()
2015-11-04 15:25:48 +03:00
2016-10-13 12:11:58 +03:00
if c.closed {
return nil, pool.ErrClosed
}
if len(c.cmds) == 0 {
return c.cmds, nil
2015-03-18 13:41:24 +03:00
}
2014-05-11 11:42:40 +04:00
cmds := c.cmds
c.cmds = nil
return cmds, c.exec(cmds)
}
func (c *Pipeline) pipelined(fn func(*Pipeline) error) ([]Cmder, error) {
if err := fn(c); err != nil {
return nil, err
}
cmds, err := c.Exec()
_ = c.Close()
return cmds, err
}
func execCmds(cn *pool.Conn, cmds []Cmder) ([]Cmder, error) {
if err := writeCmd(cn, cmds...); err != nil {
2014-05-11 11:42:40 +04:00
setCmdsErr(cmds, err)
2015-06-04 11:50:24 +03:00
return cmds, err
}
2014-05-11 11:42:40 +04:00
var firstCmdErr error
2015-06-04 11:50:24 +03:00
var failedCmds []Cmder
for _, cmd := range cmds {
2015-10-07 17:09:20 +03:00
err := cmd.readReply(cn)
2015-06-04 11:50:24 +03:00
if err == nil {
continue
}
if firstCmdErr == nil {
2015-03-18 13:41:24 +03:00
firstCmdErr = err
}
if internal.IsRetryableError(err) {
2015-06-04 11:50:24 +03:00
failedCmds = append(failedCmds, cmd)
}
}
2015-06-04 11:50:24 +03:00
return failedCmds, firstCmdErr
}