-
Notifications
You must be signed in to change notification settings - Fork 18
/
pool.go
100 lines (85 loc) · 1.92 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
package redis_timeseries_go
import (
"fmt"
"math/rand"
"sync"
"time"
"github.com/gomodule/redigo/redis"
)
type ConnPool interface {
Get() redis.Conn
Close() error
}
type SingleHostPool struct {
*redis.Pool
}
func NewSingleHostPool(host string, authPass *string) *SingleHostPool {
ret := &redis.Pool{
Dial: dialFuncWrapper(host, authPass),
TestOnBorrow: testOnBorrow,
MaxIdle: maxConns,
}
return &SingleHostPool{ret}
}
type MultiHostPool struct {
sync.Mutex
pools map[string]*redis.Pool
hosts []string
authPass *string
}
func NewMultiHostPool(hosts []string, authPass *string) *MultiHostPool {
return &MultiHostPool{
pools: make(map[string]*redis.Pool, len(hosts)),
hosts: hosts,
authPass: authPass,
}
}
func (p *MultiHostPool) Get() redis.Conn {
p.Lock()
defer p.Unlock()
host := p.hosts[rand.Intn(len(p.hosts))]
pool, found := p.pools[host]
if !found {
pool = &redis.Pool{
Dial: dialFuncWrapper(host, p.authPass),
TestOnBorrow: testOnBorrow,
MaxIdle: maxConns,
}
p.pools[host] = pool
}
return pool.Get()
}
func dialFuncWrapper(host string, authPass *string) func() (redis.Conn, error) {
return func() (redis.Conn, error) {
conn, err := redis.Dial("tcp", host)
if err != nil {
return conn, err
}
if authPass != nil {
_, err = conn.Do("AUTH", *authPass)
}
return conn, err
}
}
func testOnBorrow(c redis.Conn, t time.Time) (err error) {
if time.Since(t) > time.Millisecond {
_, err = c.Do("PING")
}
return err
}
func (p *MultiHostPool) Close() (err error) {
p.Lock()
defer p.Unlock()
for host, pool := range p.pools {
poolErr := pool.Close()
//preserve pool error if not nil but continue
if poolErr != nil {
if err == nil {
err = fmt.Errorf("Error closing pool for host %s. Got %v.", host, poolErr)
} else {
err = fmt.Errorf("%v Error closing pool for host %s. Got %v.", err, host, poolErr)
}
}
}
return
}