-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpool.go
65 lines (59 loc) · 1.02 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
package ssdb
import (
"sync"
"time"
)
type Pool struct {
mu sync.Mutex
cons []*conn
curr int
ticker *time.Ticker
}
var (
releaseWait sync.WaitGroup
)
func NewPool(options *Options) (*Pool, error) {
pool := &Pool{
mu: sync.Mutex{},
cons: make([]*conn, options.PoolSize),
curr: 0,
ticker: time.NewTicker(time.Duration(5 * time.Second)),
}
for j := 0; j < options.PoolSize; j++ {
netcon, err := dial(options)
if err != nil {
return nil, err
}
pool.cons[j] = newConn(netcon, options)
}
go func() {
for t := range pool.ticker.C {
// check alive
for _, c := range pool.cons {
c.Ping(t)
}
}
}()
return pool, nil
}
func (p *Pool) Release() {
p.ticker.Stop()
releaseWait.Wait()
for _, c := range p.cons {
c.close()
}
return
}
func (p *Pool) Do(cmd string, args ...interface{}) *Reply {
p.mu.Lock()
if p.curr == len(p.cons) {
p.curr = 0
}
c := p.cons[p.curr]
p.curr++
p.mu.Unlock()
releaseWait.Add(1)
reply := c.Do(cmd, args...)
releaseWait.Done()
return reply
}