-
Notifications
You must be signed in to change notification settings - Fork 2
/
redis.go
102 lines (86 loc) · 2.4 KB
/
redis.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
/*
-------------------------------------------------
Author : Zhang Fan
date: 2020/6/9
Description :
-------------------------------------------------
*/
package zconn
import (
"context"
"errors"
"fmt"
"time"
"github.com/go-redis/redis/v8"
)
type redisConnector struct{}
var _ IConnector = (*redisConnector)(nil)
type RedisConfig struct {
Address []string // [host1:port1, host2:port2]
Password string
DB int
IsCluster bool
PoolSize int
ReadTimeout int64 // 超时(毫秒
WriteTimeout int64 // 超时(毫秒
DialTimeout int64 // 超时(毫秒
Ping bool // 开始连接时是否ping确认连接情况
}
func (*redisConnector) NewEmptyConfig() interface{} {
return new(RedisConfig)
}
func (*redisConnector) Connect(config interface{}) (instance interface{}, err error) {
conf := config.(*RedisConfig)
if len(conf.Address) == 0 {
return nil, errors.New("请检查redis配置的address")
}
var c redis.UniversalClient
if conf.IsCluster {
c = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: conf.Address,
Password: conf.Password,
PoolSize: conf.PoolSize,
ReadTimeout: time.Duration(conf.ReadTimeout * 1e6),
WriteTimeout: time.Duration(conf.WriteTimeout * 1e6),
DialTimeout: time.Duration(conf.DialTimeout * 1e6),
})
} else {
c = redis.NewClient(&redis.Options{
Addr: conf.Address[0],
Password: conf.Password,
DB: conf.DB,
PoolSize: conf.PoolSize,
ReadTimeout: time.Duration(conf.ReadTimeout * 1e6),
WriteTimeout: time.Duration(conf.WriteTimeout * 1e6),
DialTimeout: time.Duration(conf.DialTimeout * 1e6),
})
}
if conf.Ping {
if _, err := c.Ping(context.Background()).Result(); err != nil {
return nil, fmt.Errorf("ping失败: %s", err)
}
}
return c, nil
}
func (*redisConnector) Close(instance interface{}) error {
c := instance.(redis.UniversalClient)
return c.Close()
}
func AddRedis(config interface{}, conn_name ...string) {
AddConfig(Redis, config, conn_name...)
}
func GetRedis(conn_name ...string) (redis.UniversalClient, error) {
c, ok := GetConn(Redis, conn_name...)
if !ok {
return nil, ErrNoConn
}
if !c.IsConnect() {
return nil, ErrConnNotConnected
}
return c.Instance().(redis.UniversalClient), nil
}
func MustRedis(conn_name ...string) redis.UniversalClient {
c, err := GetRedis(conn_name...)
panicOnErr(err)
return c
}