-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcacheredis.go
137 lines (104 loc) · 2.44 KB
/
cacheredis.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
package mxcache
import (
"bytes"
"context"
"encoding/json"
"net/url"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
type redisCache struct {
ctx context.Context
cache *redis.Client
//options *redis.Options
}
func newRedisCache(u *url.URL) (MXCacher, error) {
// redis://:[email protected]/1
c := &redisCache{}
options, err := redis.ParseURL(u.String())
if err != nil {
return nil, err
}
c.cache = redis.NewClient(options)
c.ctx = context.Background()
err = c.cache.Ping(c.ctx).Err()
return c, err
}
func (c *redisCache) Ping() error {
c.cache.Ping(c.ctx).Err()
return nil
}
func (c *redisCache) Get(key string, i interface{}) error {
result := c.cache.Get(c.ctx, key)
err := result.Err()
if err != nil {
if err != redis.Nil {
return err
}
return ErrNotFound
}
val, err := result.Bytes()
if err != nil {
return err
}
if err := json.NewDecoder(bytes.NewReader(val)).Decode(i); err != nil {
return err
}
return nil
}
func (c *redisCache) Set(key string, data interface{}, ex int) error {
ttl := time.Duration(0)
if ex > 0 {
ttl = time.Duration(ex) * time.Second
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(data); err != nil {
return err
}
return c.cache.Set(c.ctx, key, buf.Bytes(), ttl).Err()
}
func (c *redisCache) Expire(pattern string) (ExpiredKeys, error) {
var exkeys ExpiredKeys
if !strings.Contains(pattern, "*") {
exkeys = append(exkeys, pattern)
return exkeys, c.cache.Del(c.ctx, pattern).Err()
}
keys, err := c.cache.Keys(c.ctx, pattern).Result()
if err != nil {
return exkeys, err
}
if len(keys) == 0 {
return exkeys, nil
}
return keys, c.cache.Del(c.ctx, keys...).Err()
}
func (c *redisCache) Incr(key string) (int64, error) {
result, err := c.cache.Incr(c.ctx, key).Result()
if err != nil {
return 0, err
}
return result, nil
}
func (c *redisCache) IncrBy(key string, value int64) (int64, error) {
result, err := c.cache.IncrBy(c.ctx, key, value).Result()
if err != nil {
return 0, err
}
return result, nil
}
func (c *redisCache) ExpireAt(key string, time time.Time) error {
return c.cache.ExpireAt(c.ctx, key, time).Err()
}
func (c *redisCache) RedisClient() *redis.Client {
return c.cache
}
func (c *redisCache) Keys(pattern string) ([]string, error) {
if pattern == "" {
pattern = "*"
}
return c.cache.Keys(c.ctx, pattern).Result()
}
func (c *redisCache) RemoveKeys(keys ...string) error {
return c.cache.Del(c.ctx, keys...).Err()
}