redis.go
2.08 KB
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
package Cache
import (
"encoding/json"
"github.com/garyburd/redigo/redis"
"time"
)
//Redis redis cache
type Redis struct {
conn *redis.Pool
}
//RedisOpts redis 连接属性
type RedisOpts struct {
Host string `yml:"host" json:"host"`
Password string `yml:"password" json:"password"`
Database int `yml:"database" json:"database"`
MaxIdle int `yml:"max_idle" json:"max_idle"`
MaxActive int `yml:"max_active" json:"max_active"`
IdleTimeout int32 `yml:"idle_timeout" json:"idle_timeout"` //second
}
//NewRedis 实例化
func NewRedis(opts *RedisOpts) *Redis {
pool := &redis.Pool{
MaxActive: opts.MaxActive,
MaxIdle: opts.MaxIdle,
IdleTimeout: time.Second * time.Duration(opts.IdleTimeout),
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", opts.Host,
redis.DialDatabase(opts.Database),
redis.DialPassword(opts.Password),
)
},
TestOnBorrow: func(conn redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := conn.Do("PING")
return err
},
}
return &Redis{pool}
}
//Get 获取一个值
func (r *Redis) Get(key string) interface{} {
conn := r.conn.Get()
defer conn.Close()
var data []byte
var err error
if data, err = redis.Bytes(conn.Do("GET", key)); err != nil {
return nil
}
var reply interface{}
if err = json.Unmarshal(data, &reply); err != nil {
return nil
}
return reply
}
//Set 设置一个值
func (r *Redis) Set(key string, val interface{}, timeout time.Duration) (err error) {
conn := r.conn.Get()
defer conn.Close()
var data []byte
if data, err = json.Marshal(val); err != nil {
return
}
_, err = conn.Do("SETEX", key, int64(timeout/time.Second), data)
return
}
//IsExist 判断key是否存在
func (r *Redis) IsExist(key string) bool {
conn := r.conn.Get()
defer conn.Close()
a, _ := conn.Do("EXISTS", key)
i := a.(int64)
if i > 0 {
return true
}
return false
}
//Delete 删除
func (r *Redis) Delete(key string) error {
conn := r.conn.Get()
defer conn.Close()
if _, err := conn.Do("DEL", key); err != nil {
return err
}
return nil
}