forked from ocean-dev/go-lottery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis_helper.go
106 lines (82 loc) · 1.86 KB
/
redis_helper.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
102
103
104
105
106
package dataSource
import (
"fmt"
"log"
"sync"
"time"
"github.com/gomodule/redigo/redis"
"go-lottery/conf"
)
var redisInst *RedisConn
var redisLock sync.Mutex
type RedisConn struct {
pool *redis.Pool
showDebug bool
}
func (this *RedisConn) Do(commandName string,
args ...interface{}) (reply interface{}, err error) {
conn := this.pool.Get()
defer conn.Close() // 将连接放回连接池
t1 := time.Now().UnixNano()
reply, err = conn.Do(commandName, args...)
if err != nil {
e := conn.Err()
if e != nil {
log.Fatal("redis_helper.Do error ", err, e)
}
}
t2 := time.Now().UnixNano()
if this.showDebug {
fmt.Printf(
"[redis] [info] [%dus] cmd=%s, args=%v, reply=%s, err=%s\n",
(t2-t1)/1000, commandName, args, reply, err,
)
}
return reply, err
}
func (this *RedisConn) ShowDebug(show bool) {
this.showDebug = show
}
func RedisInstCache() *RedisConn {
if redisInst != nil {
return redisInst
}
redisLock.Lock()
defer redisLock.Unlock()
if redisInst != nil {
return redisInst
}
return NewRedisCache()
}
func NewRedisCache() *RedisConn {
pool := redis.Pool{
Dial: func() (conn redis.Conn, e error) {
c, err := redis.Dial("tcp",
fmt.Sprintf("%s:%d",
conf.RedisCache.Host,
conf.RedisCache.Port,
),
)
if err != nil {
log.Fatal("redis_helper.NewRedisCache error ", err)
return nil, err
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
MaxIdle: 10000, // 最多连接数
MaxActive: 10000, // 最多活跃数
IdleTimeout: 0, // 超时时间
Wait: false, // 连接等待
MaxConnLifetime: 0, //最大连接时间,0 一直连接
}
redisInst = &RedisConn{pool: &pool}
redisInst.ShowDebug(true)
return redisInst
}