/
redis.go
78 lines (65 loc) · 1.84 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
package delayjob
import (
log "github.com/sirupsen/logrus"
"time"
"delay-job/config"
"github.com/garyburd/redigo/redis"
)
var (
// RedisPool RedisPool连接池实例
RedisPool *redis.Pool
)
// 初始化连接池
func initRedisPool() *redis.Pool {
pool := &redis.Pool{
MaxIdle: config.Setting.Redis.MaxIdle,
MaxActive: config.Setting.Redis.MaxActive,
IdleTimeout: 300 * time.Second,
Dial: redisDial,
TestOnBorrow: redisTestOnBorrow,
Wait: true,
}
return pool
}
// 连接redis
func redisDial() (redis.Conn, error) {
conn, err := redis.Dial(
"tcp",
config.Setting.Redis.Host,
redis.DialConnectTimeout(time.Duration(config.Setting.Redis.ConnectTimeout)*time.Millisecond),
redis.DialReadTimeout(time.Duration(config.Setting.Redis.ReadTimeout)*time.Millisecond),
redis.DialWriteTimeout(time.Duration(config.Setting.Redis.WriteTimeout)*time.Millisecond),
)
if err != nil {
log.Printf("连接redis失败#%s", err.Error())
return nil, err
}
if config.Setting.Redis.Password != "" {
if _, err := conn.Do("AUTH", config.Setting.Redis.Password); err != nil {
conn.Close()
log.Printf("redis认证失败#%s", err.Error())
return nil, err
}
}
_, err = conn.Do("SELECT", config.Setting.Redis.Db)
if err != nil {
conn.Close()
log.Printf("redis选择数据库失败#%s", err.Error())
return nil, err
}
return conn, nil
}
// 从池中取出连接后,判断连接是否有效
func redisTestOnBorrow(conn redis.Conn, t time.Time) error {
_, err := conn.Do("PING")
if err != nil {
log.Printf("从redis连接池取出的连接无效#%s", err.Error())
}
return err
}
// 执行redis命令, 执行完成后连接自动放回连接池
func execRedisCommand(command string, args ...interface{}) (interface{}, error) {
redis := RedisPool.Get()
defer redis.Close()
return redis.Do(command, args...)
}