-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn.go
90 lines (73 loc) · 1.5 KB
/
conn.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package memcache
import (
"bufio"
"net"
"sync"
"time"
)
type clientConn struct {
wg sync.WaitGroup
core *coreConnection
}
// for testing
var globalNetDial = net.Dial
func netDialNewConn(addr string, options *memcacheOptions) (netConn, error) {
nc, err := globalNetDial("tcp", addr)
if err != nil {
return netConn{}, err
}
tcpNetConn, ok := nc.(*net.TCPConn)
if ok {
if err := tcpNetConn.SetKeepAlive(true); err != nil {
return netConn{}, err
}
if err := tcpNetConn.SetKeepAlivePeriod(options.tcpKeepAliveDuration); err != nil {
return netConn{}, err
}
}
writer := bufio.NewWriterSize(nc, options.bufferSize)
return netConn{
reader: nc,
writer: writer,
closer: nc,
}, nil
}
func newConn(addr string, options ...Option) (*clientConn, error) {
opts := computeOptions(options...)
nc, err := netDialNewConn(addr, opts)
if err != nil {
return nil, err
}
c := &clientConn{
core: newCoreConnection(nc, opts),
}
c.wg.Add(1)
go func() {
defer c.wg.Done()
for {
c.core.waitForError()
if c.core.isShuttingDown() {
return
}
nc, err := netDialNewConn(addr, opts)
if err != nil {
time.Sleep(opts.retryDuration)
continue
}
c.core.resetNetConn(nc)
}
}()
return c, nil
}
func (c *clientConn) pushCommand(cmd *commandData) {
c.core.publish(cmd)
}
func (c *clientConn) shutdown() error {
c.core.shutdown()
err := c.core.sender.closeNetConn()
return err
}
func (c *clientConn) waitCloseCompleted() {
c.wg.Wait()
c.core.waitReceiverShutdown()
}