-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
81 lines (72 loc) · 1.57 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// redis.go
//
// Created by Frederic DELBOS - [email protected] on Nov 10 2014.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
//
package main
import (
"encoding/json"
"github.com/garyburd/redigo/redis"
"log"
"time"
)
var ErrCacheNotFound = redis.ErrNil
type Cache interface {
Set(string, interface{}) error
Get(string, interface{}) error
Del(string) error
Init() error
}
type RedisCache struct {
Prefix string `json:"prefix"`
Host string `json:"host"`
pool *redis.Pool
}
func (r *RedisCache) Init() error {
r.pool = &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", r.Host)
if err != nil {
log.Fatal(err)
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return nil
}
func (r *RedisCache) Set(key string, data interface{}) error {
conn := r.pool.Get()
defer conn.Close()
j, err := json.Marshal(data)
if err != nil {
return err
}
_, err = conn.Do("SET", r.Prefix+key, j)
return err
}
func (r *RedisCache) Get(key string, container interface{}) error {
conn := r.pool.Get()
defer conn.Close()
data, err := conn.Do("GET", r.Prefix+key)
if err != nil {
return err
}
if data == nil {
return ErrCacheNotFound
}
return json.Unmarshal(data.([]byte), container)
}
func (r *RedisCache) Del(key string) error {
conn := r.pool.Get()
defer conn.Close()
_, err := conn.Do("DEL", r.Prefix+key)
return err
}