-
Notifications
You must be signed in to change notification settings - Fork 1
/
redis_store.go
396 lines (326 loc) · 9.5 KB
/
redis_store.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package gocache
import (
"errors"
"time"
"github.com/go-redis/redis"
"github.com/alejandro-carstens/gocache/encoder"
)
const (
deleteLimit = 1000
redisOk = "OK"
)
var _ Cache = &RedisStore{}
// NewRedisStore validates the passed in config and creates a Cache implementation of type *RedisStore
func NewRedisStore(cnf *RedisConfig, encoder encoder.Encoder) (*RedisStore, error) {
if err := cnf.validate(); err != nil {
return nil, err
}
return &RedisStore{
prefix: prefix{
val: cnf.Prefix,
},
client: redis.NewClient(&redis.Options{
Network: cnf.Network,
Addr: cnf.Addr,
Dialer: cnf.Dialer,
OnConnect: cnf.OnConnect,
Password: cnf.Password,
DB: cnf.DB,
MaxRetries: cnf.MaxRetries,
MinRetryBackoff: cnf.MinRetryBackoff,
MaxRetryBackoff: cnf.MaxRetryBackoff,
DialTimeout: cnf.DialTimeout,
ReadTimeout: cnf.ReadTimeout,
WriteTimeout: cnf.WriteTimeout,
PoolSize: cnf.PoolSize,
MinIdleConns: cnf.MinIdleConns,
MaxConnAge: cnf.MaxConnAge,
PoolTimeout: cnf.PoolTimeout,
IdleTimeout: cnf.IdleTimeout,
IdleCheckFrequency: cnf.IdleCheckFrequency,
TLSConfig: cnf.TLSConfig,
}),
encoder: encoder,
}, nil
}
// RedisStore is the representation of the redis caching store
type RedisStore struct {
prefix
client *redis.Client
encoder encoder.Encoder
}
// GetFloat64 gets a float64 value from the store
func (s *RedisStore) GetFloat64(key string) (float64, error) {
res, err := s.get(key).Float64()
return res, checkErrNotFound(err)
}
// GetFloat32 gets a float32 value from the store
func (s *RedisStore) GetFloat32(key string) (float32, error) {
res, err := s.get(key).Float32()
return res, checkErrNotFound(err)
}
// GetInt64 gets an int64 value from the store
func (s *RedisStore) GetInt64(key string) (int64, error) {
res, err := s.get(key).Int64()
return res, checkErrNotFound(err)
}
// GetInt gets an int value from the store
func (s *RedisStore) GetInt(key string) (int, error) {
res, err := s.get(key).Int()
return res, checkErrNotFound(err)
}
// GetUint64 gets an uint64 value from the store
func (s *RedisStore) GetUint64(key string) (uint64, error) {
res, err := s.get(key).Uint64()
return res, checkErrNotFound(err)
}
// GetBool gets a bool value from the store
func (s *RedisStore) GetBool(key string) (bool, error) {
value, err := s.get(key).Result()
if err != nil {
return false, checkErrNotFound(err)
}
if isStringNumeric(value) || isStringBool(value) {
return stringToBool(value), nil
}
if err = s.encoder.Decode([]byte(value), &value); err != nil {
return false, err
}
return stringToBool(value), nil
}
// GetString gets a string value from the store
func (s *RedisStore) GetString(key string) (string, error) {
value, err := s.get(key).Result()
if err != nil {
return "", checkErrNotFound(err)
}
if isStringNumeric(value) || isStringBool(value) {
return value, nil
}
if err = s.encoder.Decode([]byte(value), &value); err != nil {
return "", err
}
return value, nil
}
// Increment increments an integer counter by a given value
func (s *RedisStore) Increment(key string, value int64) (int64, error) {
return s.client.IncrBy(s.k(key), value).Result()
}
// Decrement decrements an integer counter by a given value
func (s *RedisStore) Decrement(key string, value int64) (int64, error) {
return s.client.DecrBy(s.k(key), value).Result()
}
// Put puts a value in the given store for a predetermined amount of time in seconds
func (s *RedisStore) Put(key string, value interface{}, duration time.Duration) error {
if isNumeric(value) || isBool(value) {
return s.client.Set(s.k(key), value, duration).Err()
}
val, err := s.encoder.Encode(value)
if err != nil {
return err
}
return s.client.Set(s.k(key), val, duration).Err()
}
// Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has
// expired. If the record was successfully added true will be returned else false will be returned
func (s *RedisStore) Add(key string, value interface{}, duration time.Duration) (bool, error) {
if isNumeric(value) || isBool(value) {
res, err := s.client.Eval(redisLuaAddScript, []string{s.k(key)}, value, duration.Seconds()).String()
if err != nil && !errors.Is(err, redis.Nil) {
return false, err
}
return res == redisOk, nil
}
val, err := s.encoder.Encode(value)
if err != nil {
return false, err
}
res, err := s.client.Eval(redisLuaAddScript, []string{s.k(key)}, val, duration.Seconds()).String()
if err != nil && !errors.Is(err, redis.Nil) {
return false, err
}
return res == redisOk, nil
}
// Forever puts a value in the given store until it is forgotten/evicted
func (s *RedisStore) Forever(key string, value interface{}) error {
if isNumeric(value) || isBool(value) {
if err := s.client.Set(s.k(key), value, 0).Err(); err != nil {
return err
}
return s.client.Persist(s.k(key)).Err()
}
val, err := s.encoder.Encode(value)
if err != nil {
return err
}
if err = s.client.Set(s.k(key), val, 0).Err(); err != nil {
return err
}
return s.client.Persist(s.k(key)).Err()
}
// Flush flushes the store
func (s *RedisStore) Flush() (bool, error) {
if err := s.client.FlushDB().Err(); err != nil {
return false, err
}
return true, nil
}
// Forget forgets/evicts a given key-value pair from the store
func (s *RedisStore) Forget(key string) (bool, error) {
res, err := s.client.Del(s.k(key)).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return false, nil
} else if err != nil {
return false, err
}
return res > 0, nil
}
// ForgetMany forgets/evicts a set of given key-value pair from the store
func (s *RedisStore) ForgetMany(keys ...string) error {
if len(keys) == 0 {
return nil
}
var delKeys []string
for _, key := range keys {
delKeys = append(delKeys, s.k(key))
if len(delKeys) < deleteLimit {
continue
}
if err := s.client.Del(delKeys...).Err(); err != nil {
return checkErrNotFound(err)
}
}
if len(delKeys) == 0 {
return nil
}
if err := s.client.Del(delKeys...).Err(); err != nil {
return checkErrNotFound(err)
}
return nil
}
// PutMany puts many values in the given store until they are forgotten/evicted
func (s *RedisStore) PutMany(entries ...Entry) error {
if _, err := s.client.TxPipelined(func(pipe redis.Pipeliner) error {
for _, entry := range entries {
if isNumeric(entry.Value) || isBool(entry.Value) {
if err := pipe.Set(s.k(entry.Key), entry.Value, entry.Duration).Err(); err != nil {
return err
}
continue
}
val, err := s.encoder.Encode(entry.Value)
if err != nil {
return err
}
if err = pipe.Set(s.k(entry.Key), val, entry.Duration).Err(); err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
return nil
}
// Many gets many values from the store
func (s *RedisStore) Many(keys ...string) (Items, error) {
if len(keys) == 0 {
return nil, nil
}
var prefixedKeys = make([]string, len(keys))
for i, key := range keys {
prefixedKeys[i] = s.k(key)
}
results, err := s.client.MGet(prefixedKeys...).Result()
if err != nil {
return nil, err
}
var items = Items{}
for i, result := range results {
if len(keys) <= i {
return nil, errors.New("could not retrieve key")
}
key := keys[i]
if result == nil {
items[key] = Item{
key: key,
err: ErrNotFound,
}
continue
}
val, valid := result.(string)
if !valid {
return nil, errors.New("result is not of type string")
}
if isStringNumeric(val) || isStringBool(val) {
items[key] = Item{
key: key,
value: val,
encoder: s.encoder,
}
continue
}
items[key] = Item{
key: key,
value: val,
encoder: s.encoder,
}
}
return items, err
}
// Tags returns the taggedCache for the given store
func (s *RedisStore) Tags(names ...string) TaggedCache {
return &redisTaggedCache{
taggedCache{
store: s,
tags: &TagSet{
store: s,
names: names,
},
},
}
}
// Close closes the c releasing all open resources
func (s *RedisStore) Close() error {
return s.client.Close()
}
// Get gets the struct representation of a value from the store
func (s *RedisStore) Get(key string, entity interface{}) error {
value, err := s.get(key).Bytes()
if err != nil {
return checkErrNotFound(err)
}
return s.encoder.Decode(value, entity)
}
// Lock returns a redis implementation of the Lock interface
func (s *RedisStore) Lock(name, owner string, duration time.Duration) Lock {
return newRedisLock(s.client, name, owner, duration)
}
// Exists checks if an entry exists in the cache for the given key
func (s *RedisStore) Exists(key string) (bool, error) {
_, err := s.get(key).Result()
if err == nil {
return true, nil
} else if err != nil && isErrNotFound(err) {
return false, nil
}
return false, err
}
// Expire implementation of the Cache interface
func (s *RedisStore) Expire(key string, duration time.Duration) error {
if err := s.client.Expire(s.k(key), duration).Err(); err != nil {
return checkErrNotFound(err)
}
return nil
}
// Lpush runs the Redis lpush command (used via reflection, do not delete)
func (s *RedisStore) Lpush(segment, key string) error {
return s.client.LPush(segment, key).Err()
}
// Lrange runs the Redis lrange command (used via reflection, do not delete)
func (s *RedisStore) Lrange(key string, start, stop int64) []string {
return s.client.LRange(key, start, stop).Val()
}
func (s *RedisStore) get(key string) *redis.StringCmd {
return s.client.Get(s.k(key))
}