-
Notifications
You must be signed in to change notification settings - Fork 10
/
redis.go
117 lines (104 loc) · 2.52 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
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
110
111
112
113
114
115
116
117
package main
import (
"os"
"strconv"
"time"
"github.com/gomodule/redigo/redis"
)
var (
redisPool *redis.Pool
)
func redisConnect() error {
db, err := strconv.Atoi(os.Getenv("REDIS_DB"))
if err != nil {
return err
}
redisPool = &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", os.Getenv("REDIS_URL"), redis.DialDatabase(db))
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return nil
}
func updateKeyFields(key string, fields map[string]string) error {
redisConn := redisPool.Get()
defer redisConn.Close()
var args []interface{}
args = append(args, key)
for k, value := range fields {
args = append(args, k)
args = append(args, value)
}
_, err := redisConn.Do("HMSET", args...)
return err
}
func getKeyFields(key string) (map[string]string, error) {
redisConn := redisPool.Get()
defer redisConn.Close()
res, err := redis.StringMap(redisConn.Do("HGETALL", key))
if err == redis.ErrNil {
return nil, nil
}
return res, err
}
func deleteKey(key string) error {
redisConn := redisPool.Get()
defer redisConn.Close()
_, err := redisConn.Do("DEL", key)
return err
}
func keyExists(key string) (bool, error) {
redisConn := redisPool.Get()
defer redisConn.Close()
return redis.Bool(redisConn.Do("EXISTS", key))
}
func setKeyExpiration(key string, seconds int64) error {
redisConn := redisPool.Get()
defer redisConn.Close()
_, err := redis.Bool(redisConn.Do("EXPIRE", key, seconds))
return err
}
func getKeyExpiration(key string) (int64, error) {
redisConn := redisPool.Get()
defer redisConn.Close()
ttl, err := redis.Int64(redisConn.Do("TTL", key))
return ttl, err
}
func pushWithScore(set string, key string, score int64) (bool, error) {
redisConn := redisPool.Get()
defer redisConn.Close()
_, err := redis.Int64(redisConn.Do("ZREM", set, key))
if err != nil {
return false, err
}
count, err := redis.Int64(redisConn.Do("ZADD", set, score, key))
return count == 1, err
}
func popMinScore(set string) (string, float64, error) {
redisConn := redisPool.Get()
defer redisConn.Close()
multi, err := redis.MultiBulk(redisConn.Do("BZPOPMIN", set, 0))
var key string
var score float64
if multi != nil && len(multi) == 3 {
key, err = redis.String(multi[1], nil)
if err != nil {
return "", 0, err
}
score, err = redis.Float64(multi[2], nil)
if err != nil {
return "", 0, err
}
}
return key, score, err
}