forked from jarias/stormpath-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_cache.go
58 lines (50 loc) · 1.57 KB
/
redis_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
package stormpath
import (
"encoding/json"
"github.com/garyburd/redigo/redis"
)
//RedisCache is the default provided implementation of the Cache interface using Redis as backend
type RedisCache struct {
Conn redis.Conn
}
//Exists returns true if the key exists in the cache false otherwise
func (r RedisCache) Exists(key string) bool {
exists, err := r.Conn.Do("EXISTS", key)
if err != nil {
//Log the error but don't crash or pass it along if the cache is not working the reset should
Logger.Printf("[ERROR] %s", err)
return false
}
return exists.(int64) == 1
}
//Set stores data in the the cache for the given key
func (r RedisCache) Set(key string, data interface{}) {
Logger.Printf("[DEBUG] Setting data from cache for key [%s]", key)
jsonData, _ := json.Marshal(data)
_, err := r.Conn.Do("SET", key, string(jsonData))
if err != nil {
Logger.Printf("[ERROR] %s", err)
}
}
//Get returns the data store under key it should return an error if any occur
func (r RedisCache) Get(key string, result interface{}) error {
Logger.Printf("[DEBUG] Geting data from cache for key [%s]", key)
if !r.Exists(key) {
return nil
}
cacheData, err := r.Conn.Do("GET", key)
if err != nil {
//Log the error and return an empty slice along with the error
Logger.Printf("[ERROR] %s", err)
return err
}
return json.Unmarshal(cacheData.([]byte), result)
}
//Del deletes a key from the cache
func (r RedisCache) Del(key string) {
Logger.Printf("[DEBUG] Deleting data from cache for key [%s]", key)
_, err := r.Conn.Do("DEL", key)
if err != nil {
Logger.Printf("[ERROR] %s", err)
}
}