-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachememredis.go
65 lines (48 loc) · 1.14 KB
/
cachememredis.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
package mxcache
import (
"log"
"net/url"
"strings"
)
type memRedisCache struct {
mem MXCacher
redis MXCacher
}
func newMemRedisCache(u *url.URL) (MXCacher, error) {
// mem+redis://:[email protected]/1
c := &memRedisCache{}
c.mem, _ = newMemoryCache(u)
redisUri, _ := url.Parse(strings.SplitN(u.String(), "+", 2)[1])
if r, err := newRedisCache(redisUri); err != nil {
return nil, err
} else {
c.redis = r
}
return c, nil
}
func (c *memRedisCache) Get(key string) (interface{}, error) {
if val, _ := c.mem.Get(key); val != nil {
log.Println("mem+redis: mem")
return val, nil
}
val, err := c.redis.Get(key)
if err != nil {
return nil, err
}
if val == nil {
return nil, nil
}
rc := c.redis.(*redisCache)
keyTTL := rc.RedisClient().TTL(rc.ctx, key).Val()
c.mem.Set(key, val, int(keyTTL))
log.Println("mem+redis: redis. TTL:", keyTTL)
return val, nil
}
func (c *memRedisCache) Set(key string, data interface{}, ex int) error {
c.mem.Set(key, data, ex)
return c.redis.Set(key, data, ex)
}
func (c *memRedisCache) Expire(pattern string) (expiredKeys, error) {
c.mem.Expire(pattern)
return c.redis.Expire(pattern)
}