forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
61 lines (48 loc) · 1.37 KB
/
cache.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
// Cache utilities
// TODO: Also use a local application cache to save redis rountrips
package common
import (
"encoding/json"
"errors"
"strconv"
"github.com/karlseguin/ccache"
"github.com/mediocregopher/radix/v3"
)
var (
ErrNotFound = errors.New("Not found")
CacheKeyPrefix = "cache_"
Cache *ccache.Cache
)
// Items in the cache expire after 1 min
func GetCacheData(key string) (data []byte, err error) {
err = RedisPool.Do(radix.Cmd(&data, "GET", CacheKeyPrefix+key))
return
}
// Stores an entry in the cache and sets it to expire after expire
func SetCacheData(key string, expire int, data []byte) error {
err := RedisPool.Do(radix.Cmd(nil, "SET", CacheKeyPrefix+key, string(data), "EX", strconv.Itoa(expire)))
return err
}
// Stores an entry in the cache and sets it to expire after a minute
func SetCacheDataSimple(key string, data []byte) error {
return SetCacheData(key, 60, data)
}
// Helper methods
func SetCacheDataJson(key string, expire int, data interface{}) error {
encoded, err := json.Marshal(data)
if err != nil {
return err
}
return SetCacheData(key, expire, encoded)
}
func SetCacheDataJsonSimple(key string, data interface{}) error {
return SetCacheDataJson(key, 60, data)
}
func GetCacheDataJson(key string, dest interface{}) error {
data, err := GetCacheData(key)
if err != nil {
return err
}
err = json.Unmarshal(data, dest)
return err
}