-
Notifications
You must be signed in to change notification settings - Fork 0
/
redisCache.go
46 lines (37 loc) · 878 Bytes
/
redisCache.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
package main
import (
"encoding/json"
"time"
"github.com/go-redis/cache"
"github.com/go-redis/redis"
)
var codec *cache.Codec
func initCodec() {
_, codec = NewRedisCache(map[string]string{"server0": redisHostPort}, redisDB)
}
func NewRedisCache(hostPort map[string]string, db int) (*redis.Ring, *cache.Codec) {
ring := redis.NewRing(&redis.RingOptions{
Addrs: hostPort,
DB: db,
})
codec := &cache.Codec{
Redis: ring,
Marshal: func(v interface{}) ([]byte, error) {
return json.Marshal(v)
},
Unmarshal: func(b []byte, v interface{}) error {
return json.Unmarshal(b, v)
},
}
return ring, codec
}
func CacheSet(key string, obj interface{}) error {
return codec.Set(&cache.Item{
Key: key,
Object: obj,
Expiration: time.Hour * 24 * 365,
})
}
func CacheGet(key string, obj interface{}) error {
return codec.Get(key, obj)
}