-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathredis.go
88 lines (77 loc) · 1.64 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package hera
import (
"fmt"
"time"
"github.com/xcodecraft/hera/redis"
)
type RedisSvc struct {
connType string
ip string
port string
db string
}
var Redis *RedisSvc = nil
var redisConnection *redis.Pool = nil
func NewRedisSvc() {
Redis = &RedisSvc{
connType: "tcp",
ip: SERVER["DB_NAME"],
port: SERVER["DB_PORT"],
db: SERVER["DB_NO"],
}
}
func (this *RedisSvc) getRedisPool() redis.Conn {
if redisConnection == nil {
redisConnection = &redis.Pool{
MaxIdle: 1000,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", fmt.Sprintf("%s:%s", this.ip, this.port))
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 redisConnection.Get()
}
func String(reply interface{}, err error) (string, error) {
return redis.String(reply, err)
}
func Strings(reply interface{}, err error) ([]string, error) {
return redis.Strings(reply, err)
}
func (this *RedisSvc) DoCmd(cmd string, args ...interface{}) (interface{}, error) {
enablePool := true
var c redis.Conn
var err error
if enablePool {
c = this.getRedisPool()
if SERVER["DB_PWD"] != "" {
_, err = c.Do("AUTH", SERVER["DB_PWD"])
if err != nil {
panic(err)
}
}
} else {
c, err = redis.Dial(this.connType, fmt.Sprintf("%s:%s", this.ip, this.port))
if err != nil {
panic(err)
}
}
defer c.Close()
_, err = c.Do("SELECT", this.db)
if err != nil {
panic(err)
}
re, err := c.Do(cmd, args...)
if err != nil {
panic(err)
}
return re, err
}