-
Notifications
You must be signed in to change notification settings - Fork 0
/
connections.go
97 lines (75 loc) · 1.99 KB
/
connections.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
package kredis
import (
"context"
"fmt"
"net"
"time"
"github.com/redis/go-redis/v9"
)
type config struct {
options *redis.Options
namespace string
}
var configs map[string]*config = map[string]*config{}
var connections map[string]*redis.Client = map[string]*redis.Client{}
type RedisOption func(*redis.Options)
func SetConfiguration(name, namespace, url string, opts ...RedisOption) error {
opt, err := redis.ParseURL(url)
if err != nil {
return err
}
for _, optFn := range opts {
optFn(opt)
}
configs[name] = &config{options: opt, namespace: namespace}
return nil
}
func getConnection(name string) (*redis.Client, string, error) {
config, configured := configs[name]
if !configured {
return nil, "", fmt.Errorf("%s is not a configured configuration", name)
}
conn, ok := connections[name]
if ok {
return conn, config.namespace, nil
}
conn = redis.NewClient(config.options)
connections[name] = conn
if debugLogger != nil {
conn.AddHook(newCmdLoggingHook(debugLogger))
}
return conn, config.namespace, nil
}
type cmdLoggingHook struct {
cmdLogger logging
}
func newCmdLoggingHook(clog logging) *cmdLoggingHook {
return &cmdLoggingHook{clog}
}
func (c *cmdLoggingHook) DialHook(hook redis.DialHook) redis.DialHook {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
return hook(ctx, network, addr)
}
}
func (c *cmdLoggingHook) ProcessHook(hook redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
start := time.Now()
err := hook(ctx, cmd)
c.cmdLogger.Info(cmd, time.Since(start))
return err
}
}
func (c *cmdLoggingHook) ProcessPipelineHook(hook redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return func(ctx context.Context, cmds []redis.Cmder) error {
start := time.Now()
err := hook(ctx, cmds)
for idx, cmd := range cmds {
if idx == len(cmds)-1 {
c.cmdLogger.Info(cmd, time.Since(start))
} else {
c.cmdLogger.Info(cmd, time.Duration(0))
}
}
return err
}
}