-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
110 lines (91 loc) · 2.64 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
103
104
105
106
107
108
109
110
package redis
import (
"context"
"github.com/boxgo/box/pkg/config"
"github.com/boxgo/box/pkg/dummybox"
"github.com/go-redis/redis/v8"
)
type (
Redis struct {
dummybox.DummyBox
name string
client redis.UniversalClient
cfg config.SubConfigurator
masterName *config.Field
address *config.Field
password *config.Field
db *config.Field
poolSize *config.Field
minIdleConnCnt *config.Field
}
Options struct {
name string
cfg config.SubConfigurator
}
OptionFunc func(*Options)
)
const (
Nil = redis.Nil
TxFailedErr = redis.TxFailedErr
)
var (
Default = New()
ErrClosed = redis.ErrClosed
)
func New(optionFunc ...OptionFunc) *Redis {
opts := &Options{}
for _, fn := range optionFunc {
fn(opts)
}
if opts.name == "" {
opts.name = "redis.default"
} else {
opts.name = "redis." + opts.name
}
if opts.cfg == nil {
opts.cfg = config.Default
}
r := &Redis{
name: opts.name,
cfg: opts.cfg,
masterName: config.NewField(opts.name, "masterName", "The sentinel master name. Only failover clients.", ""),
address: config.NewField(opts.name, "address", "Either a single address or a seed list of host:port addresses of cluster/sentinel nodes.", []string{}),
password: config.NewField(opts.name, "password", "Redis password", ""),
db: config.NewField(opts.name, "db", "Database to be selected after connecting to the server. Only single-node and failover clients.", 0),
poolSize: config.NewField(opts.name, "poolSize", "Connection pool size", 100),
minIdleConnCnt: config.NewField(opts.name, "minIdleConnCnt", "Min idle connections.", 50),
}
opts.cfg.Mount(r.masterName, r.address, r.password, r.db, r.poolSize, r.minIdleConnCnt)
return r
}
func Client() redis.UniversalClient {
return Default.Client()
}
func (r *Redis) Name() string {
return r.name
}
func (r *Redis) Serve(ctx context.Context) error {
r.client = redis.NewUniversalClient(&redis.UniversalOptions{
MasterName: r.cfg.GetString(r.masterName),
Addrs: r.cfg.GetStringSlice(r.address),
Password: r.cfg.GetString(r.password),
DB: r.cfg.GetInt(r.db),
PoolSize: r.cfg.GetInt(r.poolSize),
MinIdleConns: r.cfg.GetInt(r.minIdleConnCnt),
})
r.client.AddHook(&Metric{
addr: r.cfg.GetStringSlice(r.address),
master: r.cfg.GetString(r.masterName),
db: r.cfg.GetInt(r.db),
})
return r.client.Ping(ctx).Err()
}
func (r *Redis) Shutdown(ctx context.Context) error {
if r.client != nil {
return r.client.Close()
}
return nil
}
func (r *Redis) Client() redis.UniversalClient {
return r.client
}