/
init.go
115 lines (96 loc) · 2.21 KB
/
init.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
package redis
import (
"crypto/tls"
"errors"
"strings"
"sync"
"time"
"github.com/go-redis/redis/v8"
"go.uber.org/zap"
. "github.com/Rayson9418/cdc/logger"
)
const (
KMasterName = "mymaster"
KRedisTypeSingle = "single"
KRedisTypeSentinel = "sentinel"
)
var (
initOnce sync.Once
globalRedisCli *redis.Client
)
func NewDefaultOpt() *Options {
opt := new(Options)
opt.Type = KRedisTypeSingle
opt.Addr = "127.0.0.1:2369"
opt.Pwd = "123456"
opt.Auth = true
return opt
}
func InitClient(opt *Options) error {
var (
err error
client *redis.Client
)
initOnce.Do(func() {
switch opt.Type {
case KRedisTypeSingle:
client, err = initSingle(opt)
case KRedisTypeSentinel:
client, err = initSentinels(opt)
default:
err = errors.New("unknown type of redis")
}
if err != nil {
return
}
globalRedisCli = client
})
return err
}
func initSingle(opt *Options) (*redis.Client, error) {
connOpt := &redis.Options{
Addr: opt.Addr,
Password: opt.Pwd,
}
if !opt.Auth {
connOpt.Password = ""
}
if opt.TLSConfig {
connOpt.TLSConfig = &tls.Config{}
}
redisCli := redis.NewClient(connOpt)
if err := redisCli.Ping(redisCli.Context()).Err(); err != nil {
Logger.Error("failed to new redis client", zap.Error(err))
return nil, err
}
return redisCli, nil
}
func initSentinels(opt *Options) (*redis.Client, error) {
failOverOptions := &redis.FailoverOptions{
MasterName: KMasterName,
SentinelAddrs: strings.Split(opt.Addr, ","),
Password: opt.Pwd,
SentinelPassword: opt.Pwd,
}
if !opt.Auth {
failOverOptions.Password = ""
}
if opt.TLSConfig {
failOverOptions.TLSConfig = &tls.Config{}
}
redisCli := redis.NewFailoverClient(failOverOptions)
if err := redisCli.Ping(redisCli.Context()).Err(); err != nil {
Logger.Error("failed to new redis client", zap.Error(err))
return nil, err
}
return redisCli, nil
}
func GetRedisClient() *redis.Client {
return globalRedisCli
}
func SetNx(key string, value interface{}, seconds time.Duration) (bool, error) {
return globalRedisCli.SetNX(globalRedisCli.Context(), key, value, seconds).Result()
}
func Del(keys ...string) error {
return globalRedisCli.Del(globalRedisCli.Context(), keys...).Err()
}