-
Notifications
You must be signed in to change notification settings - Fork 0
/
cacheredis.go
101 lines (75 loc) · 1.69 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
package mxcache
import (
"bytes"
"context"
"encoding/gob"
"net/url"
"strings"
"time"
"github.com/go-redis/redis/v8"
)
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) Get(key string) (interface{}, error) {
result := c.cache.Get(c.ctx, key)
err := result.Err()
if err != nil {
if err != redis.Nil {
return nil, err
}
return nil, nil
}
val, err := result.Bytes()
if err != nil {
return nil, err
}
var i interface{}
if err := gob.NewDecoder(bytes.NewReader(val)).Decode(&i); err != nil {
return nil, err
}
return i, 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 := gob.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) RedisClient() *redis.Client {
return c.cache
}