-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathredis.go
61 lines (56 loc) · 1.35 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
package main
import (
"bytes"
"fmt"
"reflect"
"strconv"
"time"
"github.com/gomodule/redigo/redis"
"github.com/sirupsen/logrus"
)
func execCmd(conn redis.Conn, cmd string, args ...interface{}) string {
logrus.Debugln("exec cmd:", cmd, "args:", args)
resp, err := conn.Do(cmd, args...)
if err != nil {
return err.Error()
}
return stringfyResponse(resp)
}
func stringfyResponse(resp interface{}) string {
if resp == nil {
return "<nil>"
}
switch t := resp.(type) {
case string:
return t
case []byte:
return string(t)
case int:
return strconv.Itoa(t)
case int64:
return strconv.Itoa(int(t))
case error:
return t.Error()
case []interface{}:
buf := bytes.NewBuffer(nil)
for k, v := range t {
buf.WriteString(fmt.Sprintf("%d) ", k+1) + stringfyResponse(v) + "\r\n")
}
return buf.String()
default:
logrus.Errorln("unknown resp type:", reflect.TypeOf(resp).String())
return "unknown response type"
}
}
func DialRedis(host string, port int, password string) (redis.Conn, error) {
options := []redis.DialOption{
redis.DialConnectTimeout(time.Second),
redis.DialWriteTimeout(time.Second),
redis.DialReadTimeout(time.Second),
redis.DialKeepAlive(time.Minute * 30),
}
if password != "" {
options = append(options, redis.DialPassword(password))
}
return redis.Dial("tcp4", fmt.Sprintf("%s:%d", host, port), options...)
}