-
Notifications
You must be signed in to change notification settings - Fork 3
/
redis_cluster.go
62 lines (51 loc) · 1.32 KB
/
redis_cluster.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
package data_store
import (
"context"
"sync"
"github.com/go-redis/redis/v8"
log "github.com/shyyawn/go-to/x/logging"
"github.com/shyyawn/go-to/x/source"
"github.com/spf13/viper"
)
// RedisCluster @todo: Merge with redis
type RedisCluster struct {
MasterName string `mapstructure:"name"`
Addr []string `mapstructure:"addr"`
//Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
client *redis.ClusterClient
ctx context.Context
lock sync.RWMutex
}
func (ds *RedisCluster) LoadFromConfig(key string, config *viper.Viper) error {
return source.LoadFromConfig(key, config, ds)
}
func (ds *RedisCluster) Client() *redis.ClusterClient {
if ds.client != nil {
return ds.client
}
defer ds.lock.Unlock()
ds.lock.Lock()
// Will see if need this for later use
// Maybe can have it so that it has for health checks
ds.ctx = context.Background()
ds.client = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: ds.Addr,
Password: ds.Password,
MaxRetries: 3,
PoolSize: 10,
})
err := ds.client.ForEachShard(ds.ctx, func(ctx context.Context, client *redis.Client) error {
ping, err := client.Ping(ctx).Result()
if err == nil {
log.Info(ping)
}
return err
})
if err != nil {
log.Error(err)
ds.client = nil
return nil
}
return ds.client
}