/
redis.go
490 lines (442 loc) · 15 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
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package redis
// https://github.com/yuwf/gobase
import (
"context"
"errors"
"time"
"github.com/yuwf/gobase/utils"
"github.com/rs/zerolog/log"
"github.com/gomodule/redigo/redis"
)
const CtxKey_nolog = utils.CtxKey_nolog // 不打印日志,错误日志还会打印 值:不受限制 一般写1
const CtxKey_caller = utils.CtxKey("caller") // 值:CallerDesc对象 一般情况内部使用
const CtxKey_cmddesc = utils.CtxKey("cmddesc") // 值:字符串 命令描述 一般情况内部使用
type Config struct {
Addr string `json:"addr,omitempty"` //地址,host:port
Passwd string `json:"passwd,omitempty"`
DB int `json:"db,omitempty"`
SSl int `json:"ssl,omitempty"`
PoolSize int `json:"poolsize,omitempty"` //连接池大小
MaxActiveConn int `json:"maxactiveconn,omitempty"` //最大活跃连接数量
}
// 待优化 放到Config中
var (
redisMaxIdle = 50
redisIdleTimeout = 300
redisMaxConnLifetime = 3600
)
var defaultRedis *Redis
type Redis struct {
pool *redis.Pool
// 执行命令时的回调 不使用锁,默认要求提前注册好 管道部分待完善
hook []func(ctx context.Context, cmd *RedisCommond)
}
func DefaultRedis() *Redis {
return defaultRedis
}
func InitDefaultRedis(cfg *Config) (*Redis, error) {
var err error
defaultRedis, err = NewRedis(cfg)
return defaultRedis, err
}
func NewRedis(cfg *Config) (*Redis, error) {
// 创建一个pool
pool := &redis.Pool{
MaxIdle: redisMaxIdle,
MaxActive: cfg.MaxActiveConn,
Wait: true,
IdleTimeout: time.Duration(redisIdleTimeout) * time.Second,
MaxConnLifetime: time.Duration(redisMaxConnLifetime) * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", cfg.Addr,
redis.DialPassword(cfg.Passwd),
redis.DialDatabase(cfg.DB),
redis.DialConnectTimeout(4*time.Second),
redis.DialReadTimeout(4*time.Second),
redis.DialWriteTimeout(4*time.Second),
redis.DialUseTLS(cfg.SSl == 1),
)
if err != nil {
log.Error().Err(err).Str("addr", cfg.Addr).Str("passwd", cfg.Passwd).Int("db", cfg.DB).Int("ssl", cfg.SSl).Msg("Redis Dial Fail")
return nil, err
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
}
// 测试一条连接
conn := pool.Get()
if nil != conn.Err() {
log.Error().Err(conn.Err()).Str("addr", cfg.Addr).Str("passwd", cfg.Passwd).Int("db", cfg.DB).Int("ssl", cfg.SSl).Msg("Redis Conn Fail")
return nil, conn.Err()
}
defer conn.Close()
log.Info().Str("addr", cfg.Addr).Str("passwd", cfg.Passwd).Int("db", cfg.DB).Int("ssl", cfg.SSl).Msg("Redis Conn Success")
r := &Redis{}
r.pool = pool
return r, nil
}
// Pool 暴露原始对象
func (r *Redis) Pool() *redis.Pool {
return r.pool
}
func (r *Redis) RegHook(f func(ctx context.Context, cmd *RedisCommond)) {
r.hook = append(r.hook, f)
}
func (r *Redis) Do(ctx context.Context, cmd string, args ...interface{}) (interface{}, error) {
redisCmd := r.do(ctx, cmd, args...)
return redisCmd.Reply, redisCmd.Err
}
func (r *Redis) Do2(ctx context.Context, cmd string, args ...interface{}) RedisResultBind {
return r.do(ctx, cmd, args...)
}
//do 执行命令
func (r *Redis) do(ctx context.Context, cmd string, args ...interface{}) *RedisCommond {
redisCmd := &RedisCommond{
Cmd: cmd,
Args: args,
}
if ctx != nil {
caller := ctx.Value(CtxKey_caller)
if caller != nil {
redisCmd.Caller, _ = caller.(*utils.CallerDesc)
}
}
if redisCmd.Caller == nil {
redisCmd.Caller = utils.GetCallerDesc(2)
}
r.docmd(ctx, redisCmd)
return redisCmd
}
func (r *Redis) docmd(ctx context.Context, redisCmd *RedisCommond) {
if r.pool == nil {
log.Error().Str("pos", redisCmd.Caller.Pos()).Msg("Redis pool is nil")
redisCmd.Err = errors.New("Redis pool is nil")
return
}
if len(redisCmd.CmdDesc) == 0 && ctx != nil {
cmddesc := ctx.Value(CtxKey_cmddesc)
if cmddesc != nil {
redisCmd.CmdDesc, _ = cmddesc.(string)
}
}
entry := time.Now()
con := r.pool.Get()
defer con.Close()
redisCmd.Reply, redisCmd.Err = con.Do(redisCmd.Cmd, redisCmd.Args...)
redisCmd.Elapsed = time.Since(entry)
if redisCmd.Err != nil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).Int32("elapsed", int32(redisCmd.Elapsed/time.Millisecond)).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Msg("Redis cmd fail")
} else {
logOut := true
if ctx != nil {
nolog := ctx.Value(CtxKey_nolog)
if nolog != nil {
logOut = false
}
}
if logOut {
utils.LogCtx(log.Debug(), ctx).Int32("elapsed", int32(redisCmd.Elapsed/time.Millisecond)).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis cmd success")
}
}
// 回调
for _, f := range r.hook {
f(ctx, redisCmd)
}
}
func (r *Redis) DoCmdInt(ctx context.Context, cmd string, args ...interface{}) (int, error) {
var result int
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Int(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdInt fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdInt64(ctx context.Context, cmd string, args ...interface{}) (int64, error) {
var result int64
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Int64(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdInt64 fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdUint64(ctx context.Context, cmd string, args ...interface{}) (uint64, error) {
var result uint64
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Uint64(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdUint64 fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdFloat64(ctx context.Context, cmd string, args ...interface{}) (float64, error) {
var result float64
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Float64(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdFloat64 fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdString(ctx context.Context, cmd string, args ...interface{}) (string, error) {
var result string
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.String(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdString fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdBytes(ctx context.Context, cmd string, args ...interface{}) ([]byte, error) {
var result []byte
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Bytes(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdBytes fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdBool(ctx context.Context, cmd string, args ...interface{}) (bool, error) {
var result bool
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Bool(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdBool fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdFloat64s(ctx context.Context, cmd string, args ...interface{}) ([]float64, error) {
var result []float64
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Float64s(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdFloat64s fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdStrings(ctx context.Context, cmd string, args ...interface{}) ([]string, error) {
var result []string
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Strings(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdStrings fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdByteSlices(ctx context.Context, cmd string, args ...interface{}) ([][]byte, error) {
var result [][]byte
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.ByteSlices(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdByteSlices fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdInt64s(ctx context.Context, cmd string, args ...interface{}) ([]int64, error) {
var result []int64
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Int64s(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdInt64s fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdInts(ctx context.Context, cmd string, args ...interface{}) ([]int, error) {
var result []int
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Ints(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdInts fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdStringMap(ctx context.Context, cmd string, args ...interface{}) (map[string]string, error) {
var result map[string]string
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.StringMap(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdStringMap fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdIntMap(ctx context.Context, cmd string, args ...interface{}) (map[string]int, error) {
var result map[string]int
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.IntMap(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdIntMap fail")
}
return result, redisCmd.Err
}
func (r *Redis) DoCmdInt64Map(ctx context.Context, cmd string, args ...interface{}) (map[string]int64, error) {
var result map[string]int64
redisCmd := r.do(ctx, cmd, args...)
if redisCmd.Err != nil {
return result, redisCmd.Err
}
result, redisCmd.Err = redis.Int64Map(redisCmd.Reply, redisCmd.Err)
if redisCmd.Err != nil && redisCmd.Err != redis.ErrNil {
utils.LogCtx(log.Error(), ctx).Err(redisCmd.Err).
Str("cmd", redisCmd.CmdString()).
Str("pos", redisCmd.Caller.Pos()).
Str("reply", redisCmd.ReplyString()).
Msg("Redis DoCmdInt64Map fail")
}
return result, redisCmd.Err
}
// 针对HMGET命令 调用Cmd时,参数不需要包括field
// 结构成员首字母需要大写,tag中必须是包含 `redis:"hello"` 其中hello就表示在redis中存储的field名称
// 结构成员类型 : Bool, Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr, Float32, Float64, String, []byte
// 结构成员其他类型 : 通过Json转化
// 传入的参数为结构的地址
// 参数组织调用 hmsetObjArgs hmgetObjArgs
func (r *Redis) HMGetObj(ctx context.Context, key string, v interface{}) error {
redisCmd := &RedisCommond{
Cmd: "HMGET",
Caller: utils.GetCallerDesc(1),
}
// 组织参数
redisCmd.Args = append(redisCmd.Args, key)
fargs, elemts, structtype, err := hmgetObjArgs(v)
if err != nil {
utils.LogCtx(log.Error(), ctx).Err(err).Str("pos", redisCmd.Caller.Pos()).Msg("Redis HMGetObj Param error")
return err
}
redisCmd.Args = append(redisCmd.Args, fargs...)
r.docmd(ctx, redisCmd)
if redisCmd.Err != nil {
return redisCmd.Err
}
// 回调
redisCmd.Err = redisCmd.hmgetCallback(elemts, structtype)
return redisCmd.Err
}
// 参数v 参考Redis.HMGetObj
func (r *Redis) HMSetObj(ctx context.Context, key string, v interface{}) error {
redisCmd := &RedisCommond{
Cmd: "HMSET",
Caller: utils.GetCallerDesc(1),
}
redisCmd.Args = append(redisCmd.Args, key)
fargs, err := hmsetObjArgs(v)
if err != nil {
utils.LogCtx(log.Error(), ctx).Err(err).Str("cmd", redisCmd.CmdString()).Str("pos", redisCmd.Caller.Pos()).Msg("Redis HMSetObj Param error")
return err
}
redisCmd.Args = append(redisCmd.Args, fargs...)
r.docmd(ctx, redisCmd)
return redisCmd.Err
}