redis/pipeline.go

103 lines
1.7 KiB
Go
Raw Normal View History

package redis
2014-05-11 11:42:40 +04:00
// Not thread-safe.
type Pipeline struct {
2015-01-24 15:12:48 +03:00
commandable
2014-05-11 11:42:40 +04:00
2015-01-24 15:12:48 +03:00
cmds []Cmder
client *baseClient
2014-05-11 11:42:40 +04:00
closed bool
}
2014-05-11 11:42:40 +04:00
func (c *Client) Pipeline() *Pipeline {
2015-01-24 15:12:48 +03:00
pipe := &Pipeline{
client: &baseClient{
opt: c.opt,
connPool: c.connPool,
},
2015-01-24 15:12:48 +03:00
cmds: make([]Cmder, 0, 10),
2012-08-17 22:36:48 +04:00
}
2015-01-24 15:12:48 +03:00
pipe.commandable.process = pipe.process
return pipe
2014-05-11 11:42:40 +04:00
}
2012-08-25 23:44:53 +04:00
2014-07-02 17:18:19 +04:00
func (c *Client) Pipelined(f func(*Pipeline) error) ([]Cmder, error) {
2014-05-11 11:42:40 +04:00
pc := c.Pipeline()
2014-07-02 17:18:19 +04:00
if err := f(pc); err != nil {
return nil, err
}
2014-05-11 11:42:40 +04:00
cmds, err := pc.Exec()
pc.Close()
return cmds, err
2012-08-17 22:36:48 +04:00
}
2015-01-24 15:12:48 +03:00
func (c *Pipeline) process(cmd Cmder) {
c.cmds = append(c.cmds, cmd)
}
2014-05-11 11:42:40 +04:00
func (c *Pipeline) Close() error {
c.closed = true
return nil
}
2014-05-11 11:42:40 +04:00
func (c *Pipeline) Discard() error {
if c.closed {
return errClosed
}
c.cmds = c.cmds[:0]
return nil
2012-08-20 00:19:00 +04:00
}
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() (cmds []Cmder, retErr error) {
2014-05-11 11:42:40 +04:00
if c.closed {
return nil, errClosed
}
2015-03-18 13:41:24 +03:00
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
2015-01-24 15:12:48 +03:00
c.cmds = make([]Cmder, 0, 0)
2012-08-25 23:44:53 +04:00
for i := 0; i <= c.client.opt.MaxRetries; i++ {
if i > 0 {
resetCmds(cmds)
}
cn, err := c.client.conn()
if err != nil {
setCmdsErr(cmds, err)
return cmds, err
}
retErr = c.execCmds(cn, cmds)
c.client.putConn(cn, err)
if shouldRetry(err) {
continue
}
break
}
return cmds, retErr
}
2014-05-11 11:42:40 +04:00
func (c *Pipeline) execCmds(cn *conn, cmds []Cmder) error {
2015-01-24 15:12:48 +03:00
if err := cn.writeCmds(cmds...); err != nil {
2014-05-11 11:42:40 +04:00
setCmdsErr(cmds, err)
return err
}
2014-05-11 11:42:40 +04:00
var firstCmdErr error
for _, cmd := range cmds {
2015-03-18 13:41:24 +03:00
err := cmd.parseReply(cn.rd)
if err != nil && firstCmdErr == nil {
2015-03-18 13:41:24 +03:00
firstCmdErr = err
}
}
2014-05-11 11:42:40 +04:00
return firstCmdErr
}