-
Notifications
You must be signed in to change notification settings - Fork 21
/
redis.go
68 lines (56 loc) · 1.18 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
package redis
import (
"time"
"github.com/garyburd/redigo/redis"
)
// Commands.
const (
CommandAuth = "AUTH"
CommandDecr = "DECR"
CommandEx = "EX"
CommandExec = "Exec"
CommandExpire = "EXPIRE"
CommandGet = "GET"
CommandIncr = "INCR"
CommandMulti = "MULTI"
CommandPing = "PING"
CommandSet = "SET"
)
// Defaults.
const (
defaultIdleTimeout = 240 * time.Second
defaultMaxIdle = 10
defaultNetwork = "tcp"
)
type borrowFunc func(redis.Conn, time.Time) error
type dialFunc func() (redis.Conn, error)
func Pool(addr, password string) *redis.Pool {
return &redis.Pool{
Dial: dial(addr, password),
IdleTimeout: defaultIdleTimeout,
MaxIdle: defaultMaxIdle,
TestOnBorrow: borrow,
}
}
func borrow(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do(CommandPing)
return err
}
func dial(addr, password string) dialFunc {
return func() (redis.Conn, error) {
c, err := redis.Dial(defaultNetwork, addr)
if err != nil {
return nil, err
}
if password != "" {
if _, err := c.Do(CommandAuth, password); err != nil {
c.Close()
return nil, err
}
}
return c, err
}
}