-
Notifications
You must be signed in to change notification settings - Fork 1
/
redis.go
117 lines (93 loc) · 2.23 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
package redis
import (
"context"
"encoding"
"errors"
"os"
"strings"
"time"
r "github.com/go-redis/redis/v8"
)
var Ctx context.Context
var C r.Cmdable
var Exists ExistsFunc = ExistsDefault
var SetNx SetNXFunc = SetNXDefault
var Set SetFunc = SetDefault
var Get GetFunc = GetDefault
var Del DelFunc = DelDefault
type ExistsFunc func(string) (*bool, error)
type SetNXFunc func(string, interface{}, time.Duration) error
type SetFunc func(string, interface{}, time.Duration) error
type GetFunc func(string, encoding.BinaryUnmarshaler) error
type DelFunc func(string) error
func ExistsDefault(key string) (*bool, error) {
cmd := C.Exists(Ctx, key)
exists := false
result, err := cmd.Result()
if err != nil {
return nil, err
}
if result == 1 {
exists = true
}
return &exists, cmd.Err()
}
func SetNXDefault(key string, value interface{}, exp time.Duration) error {
return C.SetNX(Ctx, key, value, exp).Err()
}
func SetDefault(key string, value interface{}, exp time.Duration) error {
return C.Set(Ctx, key, value, exp).Err()
}
func DelDefault(key string) error {
return C.Del(Ctx, key).Err()
}
func GetDefault(name string, rec encoding.BinaryUnmarshaler) error {
val, err := C.Get(Ctx, name).Result()
if err == r.Nil {
return errors.New("does_not_exist")
}
if err != nil {
return err
}
rec.UnmarshalBinary([]byte(val))
return nil
}
func init() {
addr, ok := os.LookupEnv("REDIS_ADDR")
if !ok {
addr = "localhost:6379"
}
pass, ok := os.LookupEnv("REDIS_PASS")
if !ok {
pass = ""
}
sentinels, ok := os.LookupEnv("REDIS_SENTINELS")
if ok {
sentinelList := strings.Split(sentinels, ",")
sentinelPassword, ok := os.LookupEnv("REDIS_SENTINELS_PASS")
if !ok {
sentinelPassword = ""
}
masterName, ok := os.LookupEnv("REDIS_MASTER_NAME")
if !ok {
masterName = ""
}
c := r.NewFailoverClient(&r.FailoverOptions{
MasterName: masterName,
SentinelAddrs: sentinelList,
SentinelPassword: sentinelPassword,
Password: pass, // no password set
DB: 0, // use default DB
})
C = c
}
if !ok {
c := r.NewClient(&r.Options{
Addr: addr,
Password: pass, // no password set
DB: 0, // use default DB
})
C = c
}
Ctx = context.Background()
}