-
Notifications
You must be signed in to change notification settings - Fork 35
/
pool_tcp.go
143 lines (123 loc) · 2.4 KB
/
pool_tcp.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package pool
import (
"net"
"sync"
"time"
)
//TCPPool pool info
type TCPPool struct {
Mu sync.Mutex
IdleTimeout time.Duration
conns chan *tcpIdleConn
factory func() (net.Conn, error)
close func(net.Conn) error
}
type tcpIdleConn struct {
conn net.Conn
t time.Time
}
//Get get from pool
func (c *TCPPool) Get() (net.Conn, error) {
c.Mu.Lock()
conns := c.conns
c.Mu.Unlock()
if conns == nil {
return nil, errClosed
}
for {
select {
case wrapConn := <-conns:
if wrapConn == nil {
return nil, errClosed
}
//判断是否超时,超时则丢弃
if timeout := c.IdleTimeout; timeout > 0 {
if wrapConn.t.Add(timeout).Before(time.Now()) {
//丢弃并关闭该链接
c.close(wrapConn.conn)
continue
}
}
return wrapConn.conn, nil
default:
conn, err := c.factory()
if err != nil {
return nil, err
}
return conn, nil
}
}
}
//Put put back to pool
func (c *TCPPool) Put(conn net.Conn) error {
if conn == nil {
return errRejected
}
c.Mu.Lock()
defer c.Mu.Unlock()
if c.conns == nil {
return c.close(conn)
}
select {
case c.conns <- &tcpIdleConn{conn: conn, t: time.Now()}:
return nil
default:
//连接池已满,直接关闭该链接
return c.close(conn)
}
}
//Close close all connection
func (c *TCPPool) Close() {
c.Mu.Lock()
conns := c.conns
c.conns = nil
c.factory = nil
closeFun := c.close
c.close = nil
c.Mu.Unlock()
if conns == nil {
return
}
close(conns)
for wrapConn := range conns {
closeFun(wrapConn.conn)
}
}
//IdleCount idle connection count
func (c *TCPPool) IdleCount() int {
c.Mu.Lock()
conns := c.conns
c.Mu.Unlock()
return len(conns)
}
//NewTCPPool init tcp pool
func NewTCPPool(o *Options) (*TCPPool, error) {
if err := o.validate(); err != nil {
return nil, err
}
//init pool
pool := &TCPPool{
conns: make(chan *tcpIdleConn, o.MaxCap),
factory: func() (net.Conn, error) {
target := o.nextTarget()
if target == "" {
return nil, errTargets
}
return net.DialTimeout("tcp", target, o.DialTimeout)
},
close: func(v net.Conn) error { return v.Close() },
IdleTimeout: o.IdleTimeout,
}
//danamic update targets
o.update()
//init make conns
for i := 0; i < o.InitCap; i++ {
conn, err := pool.factory()
if err != nil {
pool.Close()
return nil, err
}
pool.conns <- &tcpIdleConn{conn: conn, t: time.Now()}
}
return pool, nil
}