Repository navigation
Expand file tree
/
Copy pathredis.go
More file actions
72 lines (63 loc) · 1.69 KB
/
Copy pathredis.go
File metadata and controls
72 lines (63 loc) · 1.69 KB
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
package cache
import (
"time"
rediscache "github.com/go-redis/cache"
"github.com/go-redis/redis"
"github.com/vmihailenco/msgpack"
)
func NewRedisCache(client *redis.Client, expiration time.Duration) CacheClient {
return &redisCache{
expiration: expiration,
codec: &rediscache.Codec{
Redis: client,
Marshal: func(v interface{}) ([]byte, error) {
return msgpack.Marshal(v)
},
Unmarshal: func(b []byte, v interface{}) error {
return msgpack.Unmarshal(b, v)
},
},
}
}
type redisCache struct {
expiration time.Duration
codec *rediscache.Codec
}
func (r *redisCache) Set(item *Item) error {
expiration := item.Expiration
if expiration == 0 {
expiration = r.expiration
}
return r.codec.Set(&rediscache.Item{
Key: item.Key,
Object: item.Object,
Expiration: expiration,
})
}
func (r *redisCache) Get(key string, obj interface{}) error {
err := r.codec.Get(key, obj)
if err == rediscache.ErrCacheMiss {
return ErrCacheMiss
}
return err
}
func (r *redisCache) Delete(key string) error {
return r.codec.Delete(key)
}
type MetricsRegistry interface {
IncRedisRequest(failed bool)
ObserveRedisRequestDuration(duration time.Duration)
}
// CollectMetrics add transport wrapper that pushes metrics into the specified metrics registry
func CollectMetrics(client *redis.Client, registry MetricsRegistry) {
client.WrapProcess(func(oldProcess func(cmd redis.Cmder) error) func(cmd redis.Cmder) error {
return func(cmd redis.Cmder) error {
startTime := time.Now()
err := oldProcess(cmd)
registry.IncRedisRequest(err != nil && err != redis.Nil)
duration := time.Since(startTime)
registry.ObserveRedisRequestDuration(duration)
return err
}
})
}