-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
335 lines (284 loc) · 6.86 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
package Dragonfly
import (
"fmt"
"github.com/go-redis/redis"
"github.com/spf13/viper"
"strings"
"time"
)
// A RedisObj represents an object with string typed key and value.
type RedisObj struct {
K string
V string
}
// A RedisError represents a structured redis error.
type RedisError struct {
Action string
Key string
Val string
ErrMsg string
}
// Error returns a formatted redis error message.
func (e *RedisError) Error() string {
return fmt.Sprintf("Action[%s] Key=%s, Val=%s, %s", e.Action, e.Key, e.Val, e.ErrMsg)
}
// RedisCallers represent a client that connects to our redis DB.
type RedisCallers struct {
Client *redis.Client
}
// NewCaller initialises a new connection client to the redis DB.
func NewCallerSentinel(config *viper.Viper) *RedisCallers {
if config != nil {
mode := config.GetString("Mode")
host := config.GetString(fmt.Sprintf("%v.%v.%v", mode, "redisDB", "host"))
pass := config.GetString(fmt.Sprintf("%v.%v.%v", mode, "redisDB", "pass"))
c := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: "mymaster",
SentinelAddrs: []string{host + ":26379"},
Password: pass,
MaxRetries: 3,
DialTimeout: 500 * time.Millisecond,
ReadTimeout: 500 * time.Millisecond,
WriteTimeout: 500 * time.Millisecond,
PoolSize: 10000,
})
return &RedisCallers{
Client: c,
}
}
return nil
}
func NewCaller(config *viper.Viper) *RedisCallers {
if config != nil {
mode := config.GetString("Mode")
host := config.GetString(fmt.Sprintf("%v.%v.%v", mode, "redisDB", "host"))
pass := config.GetString(fmt.Sprintf("%v.%v.%v", mode, "redisDB", "pass"))
c := redis.NewClient(&redis.Options{
Addr: host + ":6379",
Password: pass,
MaxRetries: 3,
DialTimeout: 500 * time.Millisecond,
ReadTimeout: 500 * time.Millisecond,
WriteTimeout: 500 * time.Millisecond,
PoolSize: 10000,
})
return &RedisCallers{
Client: c,
}
}
return nil
}
// Set creates a new entry or updates an existed entry with a specified lifetime, the default lifetime is zero.
func (c *RedisCallers) Set(k, v string, exp time.Duration) (newVal string, err error) {
if validate(k, v) {
_, err = c.Client.Set(k, v, exp).Result()
if err != nil {
return newVal, &RedisError{
Action: "Set",
Key: k,
Val: v,
ErrMsg: err.Error(),
}
}
} else {
return newVal, &RedisError{
Action: "Set",
Key: k,
Val: v,
ErrMsg: "key or value is empty",
}
}
return v, nil
}
// SetInBatch creates multiple new entries or updates multiple existed entries given by a slice of RedisObj
func (c *RedisCallers) SetInBatch(objs []RedisObj) (err error) {
if len(objs) > 0 {
var KVList []string
for _, obj := range objs {
KVList = append(KVList, obj.K, obj.V)
}
statusCmd := c.Client.MSet(KVList)
if statusCmd.Err() != nil {
err = &RedisError{
Action: "Set - In Batch",
Key: "*",
Val: "*",
ErrMsg: fmt.Sprintf("error occurs when setting keys:[%#v]", objs),
}
}
return
}
return &RedisError{
Action: "Set",
Key: "*",
Val: "*",
ErrMsg: "batch is empty",
}
}
// Get gets an entry by its key.
func (c *RedisCallers) Get(k string) (v string, err error) {
if validate(k) {
v, err = c.Client.Get(k).Result()
if err != nil {
return v, &RedisError{
Action: "Get Key",
Key: k,
Val: v,
ErrMsg: err.Error(),
}
}
} else {
return v, &RedisError{
Action: "Get",
Key: k,
Val: v,
ErrMsg: "key is empty",
}
}
return v, nil
}
// Search returns any entries that fulfills the given search patten and keywords. Pattern is used to check the key
// while keywords are used to check the values of the matched keys.
// For example, assume we have {'user:1', 'aaa'}, {'user:2', 'abc'}, {'user:3', 'bbb'} three entries,
// if the given pattern is 'user:*' and the keywords is ['a'],
// the returned entries are: {'user:1', 'aaa'}, {'user:2', 'abc'}.
// * Using scan when keySpace is big
func (c *RedisCallers) SearchByScan(patten string, keywords []string, count int64) (objs []RedisObj, err error) {
if validate(patten) {
var keys []string
scanCmd := c.Client.Scan(0, patten, count)
err = scanCmd.Err()
if err != nil {
return objs, nil
}
iter := scanCmd.Iterator()
for iter.Next() {
keys = append(keys, iter.Val())
}
values := c.Client.MGet(keys...).Val()
if len(values) == len(keys) {
for idx, key := range keys {
if len(keywords) > 0 {
if match(values[idx].(string), keywords...) {
obj := RedisObj{
K: key,
V: values[idx].(string),
}
objs = append(objs, obj)
}
} else {
obj := RedisObj{
K: key,
V: values[idx].(string),
}
objs = append(objs, obj)
}
}
} else {
return objs, &RedisError{
Action: "Search",
Key: "*",
Val: "*",
ErrMsg: "Keys and values not match",
}
}
} else {
return objs, &RedisError{
Action: "Search",
Key: "*",
Val: "*",
ErrMsg: "pattern is empty",
}
}
return objs, err
}
// * Using scan when keySpace is small
func (c *RedisCallers) SearchByKeys(patten string, keywords []string) (objs []RedisObj, err error) {
if validate(patten) {
keys := c.Client.Keys(patten).Val()
values := c.Client.MGet(keys...).Val()
if len(values) == len(keys) {
for idx, key := range keys {
if len(keywords) > 0 {
if match(values[idx].(string), keywords...) {
obj := RedisObj{
K: key,
V: values[idx].(string),
}
objs = append(objs, obj)
}
} else {
obj := RedisObj{
K: key,
V: values[idx].(string),
}
objs = append(objs, obj)
}
}
} else {
return objs, &RedisError{
Action: "Search",
Key: "*",
Val: "*",
ErrMsg: "Keys and values not match",
}
}
} else {
return objs, &RedisError{
Action: "Search",
Key: "*",
Val: "*",
ErrMsg: "pattern is empty",
}
}
return objs, err
}
// Del deletes entries by their keys
func (c *RedisCallers) Del(keys ...string) error {
if validate(keys...) {
err := c.Client.Del(keys...).Err()
if err != nil {
return &RedisError{
Action: "Delete",
Key: joinKey(keys...),
Val: "",
ErrMsg: err.Error(),
}
}
} else {
return &RedisError{
Action: "Delete",
Key: "*",
Val: "*",
ErrMsg: "key(s) are empty",
}
}
return nil
}
// validate checks if inputs are empty
func validate(args ...string) (ok bool) {
for _, arg := range args {
a := strings.TrimSpace(arg)
if len(a) == 0 {
return false
}
}
return true
}
// joinKey converts a collection of keys to a string
func joinKey(keys ...string) string {
ks := ""
for _, k := range keys {
ks += k + " "
}
return ks
}
// match checks if a string contains any of the keyword in arg keywords
func match(str string, keywords ...string) bool {
for _, k := range keywords {
if str == k {
return true
}
}
return false
}