Skip to content

Commit d3a8d04

Browse files
committed
Merge pull request #97 from go-redis/fix/pool-closes-all-connections
Fix pool to close all connections when client is closed.
2 parents 3714e40 + f3f44ae commit d3a8d04

File tree

6 files changed

+276
-171
lines changed

6 files changed

+276
-171
lines changed

conn.go

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package redis
2+
3+
import (
4+
"net"
5+
"time"
6+
7+
"gopkg.in/bufio.v1"
8+
)
9+
10+
type conn struct {
11+
netcn net.Conn
12+
rd *bufio.Reader
13+
buf []byte
14+
15+
usedAt time.Time
16+
readTimeout time.Duration
17+
writeTimeout time.Duration
18+
}
19+
20+
func newConnDialer(opt *options) func() (*conn, error) {
21+
return func() (*conn, error) {
22+
netcn, err := opt.Dialer()
23+
if err != nil {
24+
return nil, err
25+
}
26+
cn := &conn{
27+
netcn: netcn,
28+
buf: make([]byte, 0, 64),
29+
}
30+
cn.rd = bufio.NewReader(cn)
31+
return cn, cn.init(opt)
32+
}
33+
}
34+
35+
func (cn *conn) init(opt *options) error {
36+
if opt.Password == "" && opt.DB == 0 {
37+
return nil
38+
}
39+
40+
// Use connection to connect to redis
41+
pool := newSingleConnPool(nil, false)
42+
pool.SetConn(cn)
43+
44+
// Client is not closed because we want to reuse underlying connection.
45+
client := newClient(opt, pool)
46+
47+
if opt.Password != "" {
48+
if err := client.Auth(opt.Password).Err(); err != nil {
49+
return err
50+
}
51+
}
52+
53+
if opt.DB > 0 {
54+
if err := client.Select(opt.DB).Err(); err != nil {
55+
return err
56+
}
57+
}
58+
59+
return nil
60+
}
61+
62+
func (cn *conn) writeCmds(cmds ...Cmder) error {
63+
buf := cn.buf[:0]
64+
for _, cmd := range cmds {
65+
buf = appendArgs(buf, cmd.args())
66+
}
67+
68+
_, err := cn.Write(buf)
69+
return err
70+
}
71+
72+
func (cn *conn) Read(b []byte) (int, error) {
73+
if cn.readTimeout != 0 {
74+
cn.netcn.SetReadDeadline(time.Now().Add(cn.readTimeout))
75+
} else {
76+
cn.netcn.SetReadDeadline(zeroTime)
77+
}
78+
return cn.netcn.Read(b)
79+
}
80+
81+
func (cn *conn) Write(b []byte) (int, error) {
82+
if cn.writeTimeout != 0 {
83+
cn.netcn.SetWriteDeadline(time.Now().Add(cn.writeTimeout))
84+
} else {
85+
cn.netcn.SetWriteDeadline(zeroTime)
86+
}
87+
return cn.netcn.Write(b)
88+
}
89+
90+
func (cn *conn) RemoteAddr() net.Addr {
91+
return cn.netcn.RemoteAddr()
92+
}
93+
94+
func (cn *conn) Close() error {
95+
return cn.netcn.Close()
96+
}

0 commit comments

Comments
 (0)