-
Notifications
You must be signed in to change notification settings - Fork 78
/
redis.go
64 lines (51 loc) · 1.24 KB
/
redis.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
package redis
import (
"github.com/mediocregopher/radix.v2/pool"
"github.com/wanghongfei/gogate/perr"
)
// Redis Client, 只能连接一个redis实例, 有连接池
type RedisClient struct {
addr string
poolSize int
connPool *pool.Pool
isConnected bool
}
func NewRedisClient(addr string, poolSize int) *RedisClient {
if poolSize < 1 {
poolSize = 1
}
return &RedisClient{
addr: addr,
poolSize: poolSize,
}
}
func (crd *RedisClient) GetString(key string) (string, error) {
resp := crd.connPool.Cmd("get", key)
if nil != resp.Err {
return "", perr.WrapSystemErrorf(resp.Err, "failed to GetString")
}
return resp.Str()
}
func (crd *RedisClient) ExeLuaInt(lua string, keys []string, args []string) (int, error) {
resp := crd.connPool.Cmd("eval", lua, len(keys), keys, args)
if nil != resp.Err {
return 0, resp.Err
}
return resp.Int()
}
func (crd *RedisClient) Close() {
crd.connPool.Empty()
crd.isConnected = false
}
func (crd *RedisClient) IsConnected() bool {
return crd.isConnected
}
func (crd *RedisClient) Connect() error {
conn, err := pool.New("tcp", crd.addr, crd.poolSize)
if err != nil {
return perr.WrapSystemErrorf(err, "failed to connect to redis")
}
crd.connPool = conn
crd.isConnected = true
return nil
}