This repository has been archived by the owner on Dec 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 279
/
redis_store.go
99 lines (88 loc) · 2.21 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
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package storage
import (
"strings"
"gopkg.in/redis.v5"
)
// RedisStore is the base of more specialized stores
type RedisStore struct {
prefix string
client *redis.Client
}
// NewRedisStore creates a new RedisStore
func NewRedisStore(client *redis.Client, prefix string) *RedisStore {
if !strings.HasSuffix(prefix, ":") {
prefix += ":"
}
return &RedisStore{
client: client,
prefix: prefix,
}
}
// Keys matching the selector, prepending the prefix to the selector if necessary
func (s *RedisStore) Keys(selector string, opts *ListOptions) ([]string, error) {
if opts != nil && opts.cacheKey != "" {
cacheExists, err := s.client.Exists(opts.cacheKey).Result()
if err != nil {
return nil, err
}
if cacheExists {
res, err := s.client.SMembers(opts.cacheKey).Result()
if err == nil {
return res, nil
}
}
}
if selector == "" {
selector = "*"
}
if !strings.HasPrefix(selector, s.prefix) {
selector = s.prefix + selector
}
var allKeys []string
var cursor uint64
for {
keys, next, err := s.client.Scan(cursor, selector, 10000).Result()
if err != nil {
return nil, err
}
allKeys = append(allKeys, keys...)
cursor = next
if cursor == 0 {
break
}
}
if opts != nil && opts.cacheKey != "" {
pipe := s.client.Pipeline()
defer pipe.Close()
pipe.Del(opts.cacheKey)
if len(allKeys) > 0 {
var allKeysAsInterface = make([]interface{}, len(allKeys))
for i, key := range allKeys {
allKeysAsInterface[i] = key
}
pipe.SAdd(opts.cacheKey, allKeysAsInterface...)
if opts.cacheTTL > 0 {
pipe.Expire(opts.cacheKey, opts.cacheTTL)
}
}
pipe.Exec()
}
return allKeys, nil
}
// Count the results matching the selector
func (s *RedisStore) Count(selector string, options *ListOptions) (int, error) {
allKeys, err := s.Keys(selector, options)
if err != nil {
return 0, err
}
return len(allKeys), nil
}
// Delete an existing record, prepending the prefix to the key if necessary
func (s *RedisStore) Delete(key string) error {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
return s.client.Del(key).Err()
}