-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis_helper.go
109 lines (100 loc) · 2.11 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
107
108
109
package g2cache
import (
"github.com/gomodule/redigo/redis"
"time"
)
func RedisPublish(channel, message string, pool *redis.Pool) error {
conn, err := getRedisConn(pool)
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Do("PUBLISH", channel, message)
return err
}
func RedisSetString(key, value string, ttl int, pool *redis.Pool) error {
conn, err := getRedisConn(pool)
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Do("SETEX", key, ttl, value)
return err
}
func RedisGetString(key string, pool *redis.Pool) (string, error) {
conn, err := getRedisConn(pool)
if err != nil {
return "", err
}
defer conn.Close()
v, err := redis.String(conn.Do("GET", key))
if err != nil {
return "", err
}
return v, nil
}
func RedisDelKey(key string, pool *redis.Pool) error {
conn, err := getRedisConn(pool)
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Do("DEL", key)
return err
}
func getRedisConn(pool *redis.Pool) (redis.Conn, error) {
conn := pool.Get()
if err := conn.Err(); err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
func GetRedisPool(conf *RedisConf) (*redis.Pool,error) {
pool := &redis.Pool{
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", conf.DSN)
if err != nil {
return nil, err
}
if conf.Pwd != "" {
if _, err := c.Do("AUTH", conf.Pwd); err != nil {
errC := c.Close()
if errC != nil {
return nil, errC
}
return nil, err
}
}
if conf.DB > 0 {
if _, err := c.Do("SELECT", conf.DB); err != nil {
errC := c.Close()
if errC != nil {
return nil, errC
}
return nil, err
}
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
MaxIdle: conf.MaxConn,
MaxActive: conf.MaxConn,
IdleTimeout: 300 * time.Second,
Wait: true,
MaxConnLifetime: 30 * time.Minute,
}
//ping
conn, err := pool.Dial()
if err != nil {
return nil, err
}
err = pool.TestOnBorrow(conn, time.Now())
if err != nil {
return nil, err
}
return pool, nil
}