/
zredisdb.go
112 lines (94 loc) · 1.96 KB
/
zredisdb.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
package gimg
import (
"errors"
"fmt"
"github.com/garyburd/redigo/redis"
"time"
)
type ZRedisDB struct {
server string
port int
pool *redis.Pool
isConnect bool
}
func NewRedisDB(s string, p int) (*ZRedisDB, error) {
addr := fmt.Sprintf("%s:%d", s, p)
pool := &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", addr)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return &ZRedisDB{
server: s,
port: p,
pool: pool,
isConnect: true,
}, nil
}
func (z *ZRedisDB) getConnect() (redis.Conn, error) {
if z.isConnect {
conn := z.pool.Get()
return conn, nil
} else {
return nil, errors.New("Can not connect db")
}
}
func (z *ZRedisDB) Exist(key string) bool {
conn, err := z.getConnect()
if err != nil {
return false
}
defer conn.Close()
isExists, _ := redis.Bool(conn.Do("EXISTS", key))
return isExists
}
func (z *ZRedisDB) Get(key string) ([]byte, error) {
conn, err := z.getConnect()
if err != nil {
return nil, errors.New("Can not connect db!")
}
defer conn.Close()
data, err := redis.Bytes(conn.Do("GET", key))
if err != nil {
return nil, err
}
return data, nil
}
func (z *ZRedisDB) Do(commandName string, args ...interface{}) (interface{}, error) {
conn, err := z.getConnect()
if err != nil {
return nil, errors.New("Can not connect db!")
}
defer conn.Close()
return conn.Do(commandName, args...)
}
func (z *ZRedisDB) Send(commandName string, args ...interface{}) error {
conn, err := z.getConnect()
if err != nil {
return errors.New("Can not connect db!")
}
defer conn.Close()
return conn.Send(commandName, args...)
}
func (z *ZRedisDB) Flush() {
if z.isConnect {
conn := z.pool.Get()
defer conn.Close()
conn.Flush()
}
}
func (z *ZRedisDB) Close() {
if z.isConnect {
z.pool.Close()
}
}