forked from scottjbarr/redis
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpool.go
More file actions
76 lines (61 loc) · 1.37 KB
/
pool.go
File metadata and controls
76 lines (61 loc) · 1.37 KB
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
package redis
import (
"math"
"net/url"
"strconv"
"time"
redigo "github.com/gomodule/redigo/redis"
)
type BorrowFunc func(c redigo.Conn, t time.Time) error
func NewPool(uri *url.URL) *redigo.Pool {
return NewPoolWithBorrowFunc(uri, PingOnBorrow)
}
func NewPoolFromURL(uri *url.URL) *redigo.Pool {
return NewPoolWithBorrowFunc(uri, PingOnBorrow)
}
func NewPoolWithBorrowFunc(u *url.URL, f BorrowFunc) *redigo.Pool {
var password string
if u.User != nil {
password, _ = u.User.Password()
}
// db ?
db, _ := strconv.ParseInt(u.Query().Get("db"), 10, 64)
return &redigo.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redigo.Conn, error) {
c, err := redigo.Dial("tcp", u.Host)
if err != nil {
return nil, err
}
if db > 0 {
if _, err := c.Do("SELECT", db); err != nil {
return nil, err
}
}
if len(password) > 0 {
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
}
return c, err
},
TestOnBorrow: f,
}
}
func NoopOnBorrow(c redigo.Conn, t time.Time) error {
return nil
}
func PingOnBorrow(c redigo.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
}
func NewSamplingBorrow(mod float64) BorrowFunc {
return func(c redigo.Conn, t time.Time) error {
if math.Mod(float64(t.Unix()), mod) != 0 {
return nil
}
return PingOnBorrow(c, t)
}
}