-
Notifications
You must be signed in to change notification settings - Fork 1
/
redis.go
79 lines (72 loc) · 2 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
78
79
/* ######################################################################
# Author: (zfly1207@126.com)
# Created Time: 2020-10-13 11:18:19
# File Name: redis.go
# Description:
####################################################################### */
package redis
import (
"time"
rds "github.com/gomodule/redigo/redis"
)
func NewRedisPool(cfg *Cfg) *rds.Pool {
pool := &rds.Pool{
MaxIdle: 20,
IdleTimeout: 60 * time.Second,
Wait: cfg.PoolWait,
Dial: func() (r rds.Conn, err error) {
return rds.Dial("tcp", cfg.DialAddr, buildDialOptions(cfg)...)
},
TestOnBorrow: func(c rds.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
if cfg.PoolMaxIdle > 0 {
pool.MaxIdle = cfg.PoolMaxIdle
}
if cfg.PoolMaxActive > 0 {
pool.MaxActive = cfg.PoolMaxActive
}
if cfg.PoolIdleTimeout > 0 {
pool.IdleTimeout = cfg.PoolIdleTimeout * time.Millisecond
}
if cfg.PoolMaxConnLifetime > 0 {
pool.MaxConnLifetime = cfg.PoolMaxConnLifetime * time.Millisecond
}
return pool
}
func buildDialOptions(cfg *Cfg) (r []rds.DialOption) {
if len(cfg.DialUsername) > 0 {
r = append(r, rds.DialUsername(cfg.DialUsername))
}
if len(cfg.DialPassword) > 0 {
r = append(r, rds.DialPassword(cfg.DialPassword))
}
if cfg.DialDatabase > 0 {
r = append(r, rds.DialDatabase(cfg.DialDatabase))
}
if cfg.DialConnectTimeout > 0 {
r = append(r, rds.DialConnectTimeout(cfg.DialConnectTimeout*time.Millisecond))
} else {
r = append(r, rds.DialConnectTimeout(1000*time.Millisecond))
}
if cfg.DialReadTimeout > 0 {
r = append(r, rds.DialReadTimeout(cfg.DialReadTimeout*time.Millisecond))
} else {
r = append(r, rds.DialReadTimeout(500*time.Millisecond))
}
if cfg.DialWriteTimeout > 0 {
r = append(r, rds.DialWriteTimeout(cfg.DialWriteTimeout*time.Millisecond))
} else {
r = append(r, rds.DialWriteTimeout(500*time.Millisecond))
}
return
}
func HasError(err error) bool {
if err != nil && err != rds.ErrNil {
return true
}
return false
}
// vim: set noexpandtab ts=4 sts=4 sw=4 :