-
Notifications
You must be signed in to change notification settings - Fork 4
/
redis_cache.go
133 lines (102 loc) · 2.11 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// Cache object to redis automatically by registering
// callback to gorm
package goal
import (
"encoding/json"
"fmt"
"github.com/garyburd/redigo/redis"
)
// RedisCache implements Cacher interface
type RedisCache struct{}
// Get returns data for a key
func (cache *RedisCache) Get(key string, val interface{}) error {
conn, err := pool.Dial()
if err != nil {
fmt.Println(err)
return err
}
defer conn.Close()
if key == "" {
return nil
}
var reply []byte
reply, err = redis.Bytes(conn.Do("GET", key))
if err != nil {
return err
}
// Populate resource
json.Unmarshal(reply, val)
return nil
}
// Set a val for a key into Redis
func (cache *RedisCache) Set(key string, val interface{}) error {
conn, err := pool.Dial()
if err != nil {
fmt.Println(err)
return err
}
defer conn.Close()
var data []byte
data, err = json.Marshal(val)
if err != nil {
return err
}
_, err = conn.Do("SET", key, data)
return err
}
// Delete a key from Redis
func (cache *RedisCache) Delete(key string) error {
conn, err := pool.Dial()
if err != nil {
fmt.Println(err)
return err
}
defer conn.Close()
_, err = conn.Do("DEL", key)
return err
}
// Exists checks if a key exists inside Redis
func (cache *RedisCache) Exists(key string) (bool, error) {
conn, err := pool.Dial()
if err != nil {
fmt.Println(err)
return false, err
}
defer conn.Close()
var reply bool
reply, err = redis.Bool(conn.Do("EXISTS", key))
return reply, err
}
var pool *redis.Pool
// InitRedisPool initializes Redis and connection pool
func (cache *RedisCache) InitRedisPool(p *redis.Pool) error {
pool = p
conn, err := pool.Dial()
if err != nil {
pool = nil
return err
}
defer conn.Close()
return nil
}
// Pool returns global connection pool
func Pool() *redis.Pool {
return pool
}
// RedisClearAll clear all data from connection's CURRENT database
func RedisClearAll() error {
if pool == nil {
return nil
}
conn, err := pool.Dial()
if err != nil {
fmt.Println(err)
return err
}
defer conn.Close()
_, err = conn.Do("FLUSHDB")
if err != nil {
fmt.Println("Error clear redis ", err)
}
return err
}