forked from keimoon/gore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline.go
69 lines (63 loc) · 1.52 KB
/
pipeline.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package gore
import (
"time"
)
// Pipeline keeps a list of command for sending to redis once, saving network roundtrip
type Pipeline struct {
commands []*Command
}
// NewPipeline returns new Pipeline
func NewPipeline() *Pipeline {
return &Pipeline{
commands: []*Command{},
}
}
// Add appends new commands to the pipeline
func (p *Pipeline) Add(cmd ...*Command) {
p.commands = append(p.commands, cmd...)
}
// Reset clears all command in the pipeline
func (p *Pipeline) Reset() {
p.commands = []*Command{}
}
// Run sends the pipeline and returns a slice of Reply
func (p *Pipeline) Run(conn *Conn) (r []*Reply, err error) {
if len(p.commands) == 0 {
return nil, nil
}
if conn.state != connStateConnected {
return nil, ErrNotConnected
}
conn.Lock()
defer func() {
conn.Unlock()
if err != nil {
conn.fail()
}
}()
if conn.RequestTimeout != 0 {
conn.tcpConn.SetWriteDeadline(time.Now().Add(conn.RequestTimeout * time.Duration(len(p.commands)/10+1)))
}
for _, cmd := range p.commands {
err = cmd.writeCommand(conn)
if err != nil {
return nil, ErrWrite
}
}
err = conn.wb.Flush()
if err != nil {
return nil, ErrWrite
}
if conn.RequestTimeout != 0 {
conn.tcpConn.SetReadDeadline(time.Now().Add(conn.RequestTimeout * time.Duration(len(p.commands)/10+1)))
}
replies := make([]*Reply, len(p.commands))
for i := range replies {
rep, err := readReply(conn)
if err != nil {
return nil, err
}
replies[i] = rep
}
return replies, nil
}