-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
redis.go
77 lines (67 loc) · 1.72 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
/*
Package redis contains shared Redis functionality for the metric sets
*/
package redis
import (
"strings"
"time"
"github.com/elastic/beats/libbeat/logp"
rd "github.com/garyburd/redigo/redis"
)
// ParseRedisInfo parses the string returned by the INFO command
// Every line is split up into key and value
func ParseRedisInfo(info string) map[string]string {
// Feed every line into
result := strings.Split(info, "\r\n")
// Load redis info values into array
values := map[string]string{}
for _, value := range result {
// Values are separated by :
parts := ParseRedisLine(value, ":")
if len(parts) == 2 {
values[parts[0]] = parts[1]
}
}
return values
}
// ParseRedisLine parses a single line returned by INFO
func ParseRedisLine(s string, delimeter string) []string {
return strings.Split(s, delimeter)
}
// FetchRedisInfo returns a map of requested stats.
func FetchRedisInfo(stat string, c rd.Conn) (map[string]string, error) {
defer c.Close()
out, err := rd.String(c.Do("INFO", stat))
if err != nil {
logp.Err("Error retrieving INFO stats: %v", err)
return nil, err
}
return ParseRedisInfo(out), nil
}
// CreatePool creates a redis connection pool
func CreatePool(
host, password, network string,
maxConn int,
idleTimeout, connTimeout time.Duration,
) *rd.Pool {
return &rd.Pool{
MaxIdle: maxConn,
IdleTimeout: idleTimeout,
Dial: func() (rd.Conn, error) {
c, err := rd.Dial(network, host,
rd.DialConnectTimeout(connTimeout),
rd.DialReadTimeout(connTimeout),
rd.DialWriteTimeout(connTimeout))
if err != nil {
return nil, err
}
if password != "" {
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
}
return c, err
},
}
}