forked from go-xorm/xorm-redis-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_cacher.go
333 lines (282 loc) · 8.47 KB
/
redis_cacher.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package xormrediscache
import (
"bytes"
"encoding/gob"
"fmt"
"hash/crc32"
"github.com/garyburd/redigo/redis"
"github.com/go-xorm/core"
// "log"
"reflect"
// "strconv"
"time"
"unsafe"
)
const (
DEFAULT_EXPIRATION = time.Duration(0)
FOREVER_EXPIRATION = time.Duration(-1)
LOGGING_PREFIX = "[redis_cacher]"
)
// Wraps the Redis client to meet the Cache interface.
type RedisCacher struct {
pool *redis.Pool
defaultExpiration time.Duration
Logger core.ILogger
}
// New a Redis Cacher, host as IP endpoint, i.e., localhost:6379, provide empty string or nil if Redis server doesn't
// require AUTH command, defaultExpiration sets the expire duration for a key to live. Until redigo supports
// sharding/clustering, only one host will be in hostList
//
// engine.SetDefaultCacher(xormrediscache.NewRedisCacher("localhost:6379", "", xormrediscache.DEFAULT_EXPIRATION, engine.Logger))
//
// or set MapCacher
//
// engine.MapCacher(&user, xormrediscache.NewRedisCacher("localhost:6379", "", xormrediscache.DEFAULT_EXPIRATION, engine.Logger))
//
func NewRedisCacher(host string, password string, defaultExpiration time.Duration, logger core.ILogger) *RedisCacher {
var pool = &redis.Pool{
MaxIdle: 5,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
// the redis protocol should probably be made sett-able
c, err := redis.Dial("tcp", host)
if err != nil {
return nil, err
}
if len(password) > 0 {
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
} else {
// check with PING
if _, err := c.Do("PING"); err != nil {
c.Close()
return nil, err
}
}
return c, err
},
// custom connection test method
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if _, err := c.Do("PING"); err != nil {
return err
}
return nil
},
}
return MakeRedisCacher(pool, defaultExpiration, logger)
}
// MakeRedisCacher build a cacher based on redis.Pool
func MakeRedisCacher(pool *redis.Pool, defaultExpiration time.Duration, logger core.ILogger) *RedisCacher {
return &RedisCacher{pool: pool, defaultExpiration: defaultExpiration, Logger: logger}
}
func exists(conn redis.Conn, key string) bool {
existed, _ := redis.Bool(conn.Do("EXISTS", key))
return existed
}
func (c *RedisCacher) logErrf(format string, contents ...interface{}) {
if c.Logger != nil {
c.Logger.Errorf(fmt.Sprintf("%s %s", LOGGING_PREFIX, format), contents...)
}
}
func (c *RedisCacher) logDebugf(format string, contents ...interface{}) {
if c.Logger != nil {
c.Logger.Debugf(fmt.Sprintf("%s %s", LOGGING_PREFIX, format), contents...)
}
}
func (c *RedisCacher) getBeanKey(tableName string, id string) string {
return fmt.Sprintf("xorm:bean:%s:%s", tableName, id)
}
func (c *RedisCacher) getSqlKey(tableName string, sql string) string {
// hash sql to minimize key length
crc := crc32.ChecksumIEEE([]byte(sql))
return fmt.Sprintf("xorm:sql:%s:%d", tableName, crc)
}
// Delete all xorm cached objects
func (c *RedisCacher) Flush() error {
// conn := c.pool.Get()
// defer conn.Close()
// _, err := conn.Do("FLUSHALL")
// return err
return c.delObject("xorm:*")
}
func (c *RedisCacher) getObject(key string) interface{} {
conn := c.pool.Get()
defer conn.Close()
raw, err := conn.Do("GET", key)
if raw == nil {
return nil
}
item, err := redis.Bytes(raw, err)
if err != nil {
c.logErrf("redis.Bytes failed: %s", err)
return nil
}
value, err := c.deserialize(item)
return value
}
func (c *RedisCacher) GetIds(tableName, sql string) interface{} {
sqlKey := c.getSqlKey(tableName, sql)
c.logDebugf(" GetIds|tableName:%s|sql:%s|key:%s", tableName, sql, sqlKey)
return c.getObject(sqlKey)
}
func (c *RedisCacher) GetBean(tableName string, id string) interface{} {
beanKey := c.getBeanKey(tableName, id)
c.logDebugf("[xorm/redis_cacher] GetBean|tableName:%s|id:%s|key:%s", tableName, id, beanKey)
return c.getObject(beanKey)
}
func (c *RedisCacher) putObject(key string, value interface{}) {
c.invoke(c.pool.Get().Do, key, value, c.defaultExpiration)
}
func (c *RedisCacher) PutIds(tableName, sql string, ids interface{}) {
sqlKey := c.getSqlKey(tableName, sql)
c.logDebugf("PutIds|tableName:%s|sql:%s|key:%s|obj:%s|type:%v", tableName, sql, sqlKey, ids, reflect.TypeOf(ids))
c.putObject(sqlKey, ids)
}
func (c *RedisCacher) PutBean(tableName string, id string, obj interface{}) {
beanKey := c.getBeanKey(tableName, id)
c.logDebugf("PutBean|tableName:%s|id:%s|key:%s|type:%v", tableName, id, beanKey, reflect.TypeOf(obj))
c.putObject(beanKey, obj)
}
func (c *RedisCacher) delObject(key string) error {
c.logDebugf("delObject key:[%s]", key)
conn := c.pool.Get()
defer conn.Close()
if !exists(conn, key) {
c.logErrf("delObject key:[%s] err: %v", key, core.ErrCacheMiss)
return core.ErrCacheMiss
}
_, err := conn.Do("DEL", key)
return err
}
func (c *RedisCacher) delObjects(key string) error {
c.logDebugf("delObjects key:[%s]", key)
conn := c.pool.Get()
defer conn.Close()
cursor := 0
args := []interface{}{cursor, "MATCH", key, "COUNT", 5000}
for cursor != -1 {
args[0] = cursor
replys, err := conn.Do("SCAN", args...)
if err != nil {
return err
}
if err == nil {
for index, reply := range replys.([]interface{}) {
if index == 0 {
cursor, _ = redis.Int(reply, nil)
if cursor == 0 {
cursor = -1
}
} else {
keys, _ := redis.Values(reply, nil)
if len(keys) > 0 {
c.logDebugf("delObjects keys: %s", keys)
conn.Do("DEL", keys...)
}
}
}
}
}
return nil
}
func (c *RedisCacher) DelIds(tableName, sql string) {
c.delObject(c.getSqlKey(tableName, sql))
}
func (c *RedisCacher) DelBean(tableName string, id string) {
c.delObject(c.getBeanKey(tableName, id))
}
func (c *RedisCacher) ClearIds(tableName string) {
c.delObjects(fmt.Sprintf("xorm:sql:%s:*", tableName))
}
func (c *RedisCacher) ClearBeans(tableName string) {
c.delObjects(c.getBeanKey(tableName, "*"))
}
func (c *RedisCacher) invoke(f func(string, ...interface{}) (interface{}, error),
key string, value interface{}, expires time.Duration) error {
switch expires {
case DEFAULT_EXPIRATION:
expires = c.defaultExpiration
case FOREVER_EXPIRATION:
expires = time.Duration(0)
}
b, err := c.serialize(value)
if err != nil {
return err
}
conn := c.pool.Get()
defer conn.Close()
if expires > 0 {
_, err := f("SETEX", key, int32(expires/time.Second), b)
return err
} else {
_, err := f("SET", key, b)
return err
}
}
func (c *RedisCacher) serialize(value interface{}) ([]byte, error) {
err := c.registerGobConcreteType(value)
if err != nil {
return nil, err
}
if reflect.TypeOf(value).Kind() == reflect.Struct {
return nil, fmt.Errorf("serialize func only take pointer of a struct")
}
var b bytes.Buffer
encoder := gob.NewEncoder(&b)
c.logDebugf("serialize type:%v", reflect.TypeOf(value))
err = encoder.Encode(&value)
if err != nil {
c.logErrf("gob encoding '%s' failed: %s|value:%v", value, err, value)
return nil, err
}
return b.Bytes(), nil
}
func (c *RedisCacher) deserialize(byt []byte) (ptr interface{}, err error) {
b := bytes.NewBuffer(byt)
decoder := gob.NewDecoder(b)
var p interface{}
err = decoder.Decode(&p)
if err != nil {
c.logErrf("decode failed: %v", err)
return
}
v := reflect.ValueOf(p)
c.logDebugf("deserialize type:%v", v.Type())
if v.Kind() == reflect.Struct {
var pp interface{} = &p
datas := reflect.ValueOf(pp).Elem().InterfaceData()
sp := reflect.NewAt(v.Type(),
unsafe.Pointer(datas[1])).Interface()
ptr = sp
vv := reflect.ValueOf(ptr)
c.logDebugf("deserialize convert ptr type:%v | CanAddr:%t", vv.Type(), vv.CanAddr())
} else {
ptr = p
}
return
}
func (c *RedisCacher) registerGobConcreteType(value interface{}) error {
t := reflect.TypeOf(value)
c.logDebugf("registerGobConcreteType:%v", t)
switch t.Kind() {
case reflect.Ptr:
v := reflect.ValueOf(value)
i := v.Elem().Interface()
gob.Register(&i)
case reflect.Struct, reflect.Map, reflect.Slice:
gob.Register(value)
case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
// do nothing since already registered known type
default:
return fmt.Errorf("unhandled type: %v", t)
}
return nil
}
func (c *RedisCacher) GetPool() (*redis.Pool, error) {
return c.pool, nil
}
func (c *RedisCacher) SetPool(pool *redis.Pool) {
c.pool = pool
}