-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool.go
101 lines (80 loc) · 1.94 KB
/
pool.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
89
90
91
92
93
94
95
96
97
98
99
100
101
package redis
import (
rg "github.com/garyburd/redigo/redis"
"github.com/kucuny/redigocon"
"time"
)
type (
PoolConnection interface {
RedisCommands
PoolCommands
}
ConnectionPoolConfig struct {
MaxIdle int
MaxActive int
IdleTimeout time.Duration
}
)
var DefaultConnectionPoolConfig = ConnectionPoolConfig{
MaxIdle: 60,
MaxActive: 100,
IdleTimeout: 30,
}
func CreatePool(serverAddr, auth, db string, poolConfig ConnectionPoolConfig) (PoolConnection, error) {
dialer := func() (rg.Conn, error) {
return redigocon.Connect(serverAddr, auth, db)
}
tester := func(c rg.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
}
config := getConnectionPoolConfig(&poolConfig)
pool := &rg.Pool{
MaxIdle: config.MaxIdle,
IdleTimeout: config.IdleTimeout,
MaxActive: config.MaxActive,
Dial: dialer,
TestOnBorrow: tester,
}
con := &connection{p: pool}
return con, nil
}
func CreatePoolUri(uri string, poolConfig ConnectionPoolConfig) (PoolConnection, error) {
dialer := func() (rg.Conn, error) {
return redigocon.ConnectUrl(uri)
}
tester := func(c rg.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
}
config := getConnectionPoolConfig(&poolConfig)
pool := &rg.Pool{
MaxIdle: config.MaxIdle,
IdleTimeout: config.IdleTimeout,
Dial: dialer,
TestOnBorrow: tester,
}
con := &connection{p: pool}
return con, nil
}
func getConnectionPoolConfig(config *ConnectionPoolConfig) ConnectionPoolConfig {
if config.IdleTimeout == 0 || config.MaxIdle == 0 || config.MaxActive == 0 {
return DefaultConnectionPoolConfig
} else {
return *config
}
}
func (con *connection) GetConnection() (PoolConnection, error) {
c := con.p.Get()
resCon := &connection{c: c}
return resCon, nil
}
func (con *connection) ActiveCount() int {
return con.p.ActiveCount()
}
func (con *connection) Release() {
con.c.Close()
}
func (con *connection) PoolClose() {
con.p.Close()
}