-
Notifications
You must be signed in to change notification settings - Fork 8
/
pool.go
107 lines (98 loc) · 1.95 KB
/
pool.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
package pool
import (
"errors"
"fmt"
"sync"
)
var (
// ErrClosed is the error resulting if the pool is closed via pool.Close().
ErrClosed = errors.New("pool is closed")
)
// Pool common connection pool
type Pool struct {
// New create connection function
New func() interface{}
// Ping check connection is ok
Ping func(interface{}) bool
// Close close connection
Close func(interface{})
store chan interface{}
mu sync.Mutex
}
// New create a pool with capacity
func New(initCap, maxCap int, newFunc func() interface{}) (*Pool, error) {
if maxCap == 0 || initCap > maxCap {
return nil, fmt.Errorf("invalid capacity settings")
}
p := new(Pool)
p.store = make(chan interface{}, maxCap)
if newFunc != nil {
p.New = newFunc
}
for i := 0; i < initCap; i++ {
v, err := p.create()
if err != nil {
return p, err
}
p.store <- v
}
return p, nil
}
// Len returns current connections in pool
func (p *Pool) Len() int {
return len(p.store)
}
// Get returns a conn form store or create one
func (p *Pool) Get() (interface{}, error) {
if p.store == nil {
// pool aleardy destroyed, returns error
return nil, ErrClosed
}
for {
select {
case v := <-p.store:
if p.Ping != nil && !p.Ping(v) {
continue
}
return v, nil
default:
// pool is empty, returns new connection
return p.create()
}
}
}
// Put set back conn into store again
func (p *Pool) Put(v interface{}) {
select {
case p.store <- v:
return
default:
// pool is full, close passed connection
if p.Close != nil {
p.Close(v)
}
return
}
}
// Destroy clear all connections
func (p *Pool) Destroy() {
p.mu.Lock()
defer p.mu.Unlock()
if p.store == nil {
// pool aleardy destroyed
return
}
close(p.store)
for v := range p.store {
if p.Close != nil {
p.Close(v)
}
}
p.store = nil
}
func (p *Pool) create() (interface{}, error) {
if p.New == nil {
return nil, fmt.Errorf("Pool.New is nil, can not create connection")
}
return p.New(), nil
}