-
Notifications
You must be signed in to change notification settings - Fork 4
/
conn.go
145 lines (118 loc) · 2.32 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
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
144
145
package pool
import (
"fmt"
"io"
"sync"
)
var ErrMaxConn = fmt.Errorf("maximum connections reached")
// ConnPool manages the life cycle of connections
type ConnPool struct {
sync.RWMutex
// New is used to create a new connection when necessary.
New func() (io.Closer, error)
// Ping is use to check the conn fetched from pool
Ping func(io.Closer) error
Address string
MaxConns int
MaxIdle int
TestOnBorrow bool
active int
free []io.Closer
}
func Create(address string, maxConns int, maxIdle int) *ConnPool {
return &ConnPool{
Address: address,
MaxConns: maxConns,
MaxIdle: maxIdle,
}
}
func (this *ConnPool) Get() (conn io.Closer, err error) {
conn = this.tryFree()
if conn != nil {
if this.TestOnBorrow {
err = this.Ping(conn)
if err != nil {
this.decreActive() //bug fix: 如果不加decrease, 当 free不为空 + server端重启时 就会导致active大于实际情况不符
conn.Close()
conn = this.tryFree()
err = nil
}
}
if conn != nil {
return
}
}
if this.reachedMax() {
return nil, ErrMaxConn
}
conn, err = this.New()
if err != nil {
return
}
if this.TestOnBorrow {
err = this.Ping(conn)
if err != nil {
conn.Close()
return nil, err
}
}
this.increActive()
return
}
func (this *ConnPool) Release(conn io.Closer) {
if this.overMaxIdle() {
this.decreActive()
if conn != nil {
conn.Close()
}
} else {
this.Lock()
defer this.Unlock()
this.free = append(this.free, conn)
}
}
func (this *ConnPool) ForceClose(conn io.Closer) {
this.decreActive()
if conn != nil {
conn.Close()
}
}
func (this *ConnPool) Destroy() {
this.Lock()
defer this.Unlock()
for _, conn := range this.free {
if conn != nil {
conn.Close()
}
}
}
func (this *ConnPool) tryFree() io.Closer {
this.Lock()
defer this.Unlock()
if len(this.free) == 0 {
return nil
}
conn := this.free[0]
this.free = this.free[1:]
return conn
}
func (this *ConnPool) reachedMax() bool {
this.RLock()
defer this.RUnlock()
return this.active >= this.MaxConns
}
func (this *ConnPool) increActive() {
this.Lock()
defer this.Unlock()
this.active += 1
}
func (this *ConnPool) decreActive() {
this.Lock()
defer this.Unlock()
this.active -= 1
}
func (this *ConnPool) overMaxIdle() bool {
this.RLock()
defer this.RUnlock()
return len(this.free) >= this.MaxIdle
}