/
redis.go
68 lines (54 loc) · 1.1 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
package dependencies
import (
"context"
"fmt"
"time"
"github.com/go-redis/redis/v8"
)
type Redis interface {
Context() context.Context
Handler() *redis.Client
}
type RedisClientConfig struct {
Host string
Port int
Password string
}
type RedisClient struct {
handler *redis.Client
ctx context.Context
}
func NewRedisClient(c RedisClientConfig) Redis {
opt := &redis.Options{
Addr: fmt.Sprintf("%s:%d", c.Host, c.Port),
DB: 0,
}
if c.Password != "" {
opt.Password = c.Password
}
redisClient := redis.NewClient(opt)
// Generate context background
ctx := context.Background()
// Test connection
err := redisClient.Ping(ctx).Err()
if err != nil {
// In case of error wait for 5 sec and try again
time.Sleep(5 * time.Second)
err := redisClient.Ping(ctx).Err()
if err != nil {
panic(err)
}
}
return &RedisClient{
handler: redisClient,
ctx: ctx,
}
}
// Handler redis requested action
func (c *RedisClient) Handler() *redis.Client {
return c.handler
}
// Context for current client instance
func (c *RedisClient) Context() context.Context {
return c.ctx
}