-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
redisclient.go
173 lines (156 loc) · 4.48 KB
/
redisclient.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package redis
import (
"fmt"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/FZambia/sentinel"
"github.com/gomodule/redigo/redis"
"github.com/goharbor/harbor/src/lib/log"
)
var knownPool sync.Map
var m sync.Mutex
// PoolParam ...
type PoolParam struct {
PoolMaxIdle int
PoolMaxActive int
PoolIdleTimeout time.Duration
DialConnectionTimeout time.Duration
DialReadTimeout time.Duration
DialWriteTimeout time.Duration
}
// GetRedisPool get a named redis pool
// supported rawurl
// redis://user:pass@redis_host:port/db
// redis+sentinel://user:pass@redis_sentinel1:port1,redis_sentinel2:port2/monitor_name/db?idle_timeout_seconds=100
func GetRedisPool(name string, rawurl string, param *PoolParam) (*redis.Pool, error) {
if p, ok := knownPool.Load(name); ok {
return p.(*redis.Pool), nil
}
m.Lock()
defer m.Unlock()
// load again in case multi threads
if p, ok := knownPool.Load(name); ok {
return p.(*redis.Pool), nil
}
u, err := url.Parse(rawurl)
if err != nil {
return nil, fmt.Errorf("bad redis url: %s, %s, %s", name, rawurl, err)
}
if param == nil {
param = &PoolParam{
PoolMaxIdle: 0,
PoolMaxActive: 1,
PoolIdleTimeout: time.Minute,
DialConnectionTimeout: time.Second,
DialReadTimeout: time.Second,
DialWriteTimeout: time.Second,
}
}
if t := u.Query().Get("idle_timeout_seconds"); t != "" {
if tt, e := strconv.Atoi(t); e == nil {
param.PoolIdleTimeout = time.Second * time.Duration(tt)
}
}
log.Debug("get redis pool:", name, rawurl)
if u.Scheme == "redis" {
pool := &redis.Pool{
Dial: func() (redis.Conn, error) {
return redis.DialURL(rawurl)
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
MaxIdle: param.PoolMaxIdle,
MaxActive: param.PoolMaxActive,
IdleTimeout: param.PoolIdleTimeout,
Wait: true,
}
knownPool.Store(name, pool)
return pool, nil
} else if u.Scheme == "redis+sentinel" {
pool, err := getSentinelPool(u, param, name)
if err != nil {
return nil, err
}
knownPool.Store(name, pool)
return pool, nil
} else {
return nil, fmt.Errorf("bad redis url: not support scheme %s", u.Scheme)
}
}
func getSentinelPool(u *url.URL, param *PoolParam, name string) (*redis.Pool, error) {
ps := strings.Split(u.Path, "/")
if len(ps) < 2 {
return nil, fmt.Errorf("bad redis sentinel url: no master name, %s %s", name, u)
}
log.Debug("getSentinelPool:", u)
var sentinelOptions []redis.DialOption
if param.DialConnectionTimeout > 0 {
log.Debug(name, "sentinel DialConnectionTimeout:", param.DialConnectionTimeout)
sentinelOptions = append(sentinelOptions, redis.DialConnectTimeout(param.DialConnectionTimeout))
}
if param.DialReadTimeout > 0 {
log.Debug(name, "sentinel DialReadTimeout:", param.DialReadTimeout)
sentinelOptions = append(sentinelOptions, redis.DialReadTimeout(param.DialReadTimeout))
}
if param.DialWriteTimeout > 0 {
log.Debug(name, "sentinel DialWriteTimeout:", param.DialWriteTimeout)
sentinelOptions = append(sentinelOptions, redis.DialWriteTimeout(param.DialWriteTimeout))
}
redisOptions := sentinelOptions
if u.User != nil {
password, isSet := u.User.Password()
if isSet {
log.Debug(name, "redis has password")
redisOptions = append(redisOptions, redis.DialPassword(password))
}
}
// sentinel doesn't need select db
db := 0
if len(ps) > 2 {
db, err := strconv.Atoi(ps[2])
if err != nil {
return nil, fmt.Errorf("invalid redis db: %s, %s", ps[1], name)
}
if db != 0 {
redisOptions = append(redisOptions, redis.DialDatabase(db))
}
}
sntnl := &sentinel.Sentinel{
Addrs: strings.Split(u.Host, ","),
MasterName: ps[1],
Dial: func(addr string) (redis.Conn, error) {
log.Debug(name, "dial redis sentinel:", addr)
c, err := redis.Dial("tcp", addr, sentinelOptions...)
if err != nil {
return nil, err
}
return c, nil
},
}
pool := &redis.Pool{
Dial: func() (redis.Conn, error) {
masterAddr, err := sntnl.MasterAddr()
if err != nil {
return nil, err
}
log.Debug(name, "dial redis master:", masterAddr, "db:", db)
return redis.Dial("tcp", masterAddr, redisOptions...)
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if !sentinel.TestRole(c, "master") {
return fmt.Errorf("check role failed, %s", name)
}
return nil
},
MaxIdle: param.PoolMaxIdle,
MaxActive: param.PoolMaxActive,
IdleTimeout: param.PoolIdleTimeout,
Wait: true,
}
return pool, nil
}