2013-07-02 15:17:31 +04:00
|
|
|
package redis
|
|
|
|
|
|
|
|
type PipelineClient struct {
|
|
|
|
*Client
|
|
|
|
}
|
|
|
|
|
2013-09-17 11:35:52 +04:00
|
|
|
// TODO: rename to Pipeline
|
|
|
|
// TODO: return just *PipelineClient
|
2013-07-02 15:17:31 +04:00
|
|
|
func (c *Client) PipelineClient() (*PipelineClient, error) {
|
|
|
|
return &PipelineClient{
|
|
|
|
Client: &Client{
|
|
|
|
baseClient: &baseClient{
|
2013-09-11 20:22:10 +04:00
|
|
|
opt: c.opt,
|
2013-07-02 15:17:31 +04:00
|
|
|
connPool: c.connPool,
|
|
|
|
|
|
|
|
reqs: make([]Req, 0),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Pipelined(do func(*PipelineClient)) ([]Req, error) {
|
|
|
|
pc, err := c.PipelineClient()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer pc.Close()
|
|
|
|
|
|
|
|
do(pc)
|
|
|
|
|
|
|
|
return pc.RunQueued()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PipelineClient) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PipelineClient) DiscardQueued() {
|
|
|
|
c.reqsMtx.Lock()
|
|
|
|
c.reqs = c.reqs[:0]
|
|
|
|
c.reqsMtx.Unlock()
|
|
|
|
}
|
|
|
|
|
2013-09-17 11:35:52 +04:00
|
|
|
// TODO: rename to Run or ...
|
|
|
|
// TODO: should return error if one of the commands failed
|
2013-07-02 15:17:31 +04:00
|
|
|
func (c *PipelineClient) RunQueued() ([]Req, error) {
|
|
|
|
c.reqsMtx.Lock()
|
|
|
|
reqs := c.reqs
|
|
|
|
c.reqs = make([]Req, 0)
|
|
|
|
c.reqsMtx.Unlock()
|
|
|
|
|
|
|
|
if len(reqs) == 0 {
|
|
|
|
return []Req{}, nil
|
|
|
|
}
|
|
|
|
|
2013-09-17 11:35:52 +04:00
|
|
|
cn, err := c.conn()
|
2013-07-02 15:17:31 +04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2013-09-17 11:35:52 +04:00
|
|
|
if err := c.runReqs(reqs, cn); err != nil {
|
|
|
|
c.removeConn(cn)
|
2013-07-02 15:17:31 +04:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2013-09-17 11:35:52 +04:00
|
|
|
c.putConn(cn)
|
2013-07-02 15:17:31 +04:00
|
|
|
return reqs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PipelineClient) runReqs(reqs []Req, cn *conn) error {
|
|
|
|
err := c.writeReq(cn, reqs...)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
reqsLen := len(reqs)
|
|
|
|
for i := 0; i < reqsLen; i++ {
|
|
|
|
req := reqs[i]
|
|
|
|
val, err := req.ParseReply(cn.Rd)
|
|
|
|
if err != nil {
|
|
|
|
req.SetErr(err)
|
|
|
|
} else {
|
|
|
|
req.SetVal(val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|