-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsentinel.go
80 lines (74 loc) · 1.82 KB
/
sentinel.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
package goredis
import (
"errors"
"time"
"github.com/FZambia/sentinel"
"github.com/gomodule/redigo/redis"
)
type SentinelClient struct {
masters *redis.Pool
masterName string
}
func NewSentinelClient(masterName string, addrs []string, option *Option) *SentinelClient {
cli := &SentinelClient{}
cli.Init(masterName, addrs, option)
return cli
}
func (this *SentinelClient) Init(masterName string, addrs []string, option *Option) {
sntnl := &sentinel.Sentinel{
Addrs: addrs,
MasterName: masterName,
Dial: func(addr string) (redis.Conn, error) {
timeout := 500 * time.Millisecond
c, err := redis.DialTimeout("tcp", addr, timeout, timeout, timeout)
if err != nil {
return nil, err
}
return c, nil
},
}
this.masterName = masterName
this.masters = &redis.Pool{
MaxIdle: option.PoolMaxIdle,
MaxActive: option.PoolMaxActive,
Wait: option.PoolWait,
IdleTimeout: option.PoolIdleTimeout,
Dial: func() (redis.Conn, error) {
masterAddr, err := sntnl.MasterAddr()
if err != nil {
return nil, err
}
c, err := redis.Dial("tcp", masterAddr)
if err != nil {
return nil, err
}
if option.Password != "" {
if _, err := c.Do("AUTH", option.Password); err != nil {
c.Close()
return nil, err
}
}
if _, err := c.Do("SELECT", option.DBIndex); err != nil {
c.Close()
return nil, err
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if !sentinel.TestRole(c, "master") {
return errors.New("[redis] Role check failed")
} else {
return nil
}
},
}
}
func (this *SentinelClient) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
conn := this.masters.Get()
if conn.Err() == nil {
defer conn.Close()
return conn.Do(commandName, args...)
} else {
return nil, conn.Err()
}
}