-
Notifications
You must be signed in to change notification settings - Fork 2
/
redis.go
100 lines (79 loc) · 2.01 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
package main
import (
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"github.com/go-redis/redis/v8"
)
var (
rdb *redis.Client = nil
)
func connectToRedisServer() bool {
// return true if already connected
if rdb != nil {
return true
}
log.Debug("connecting with Redis server")
redisHost := getEnv(keyRedisHost, defaultRedisHost)
redisPort := getEnv(keyRedisPort, defaultRedisPort)
address := redisHost + ":" + redisPort
// create new Redis client if one does not exist already
redisDbStr := getEnv(keyRedisDb, defaultRedisDb)
redisDb, err := strconv.Atoi(redisDbStr)
if err != nil {
redisDb = 0
log.Warnf("invalid redis db %v. err: %v. using default db: %v", redisDbStr, err.Error(), redisDb)
}
rdb = redis.NewClient(&redis.Options{
Addr: address,
Password: "", // no password set
DB: redisDb,
})
if !pingRedisServer() {
rdb.Close()
rdb = nil
return false
}
log.Debugf("connected with Redis server [%v]", address)
return true
}
func pingRedisServer() bool {
log.Debug("pinging Redis server")
val, err := rdb.Ping(rdb.Context()).Result()
switch {
case err == redis.Nil:
return false
case err != nil:
log.Warnf("PING call failed! %v", err.Error())
return false
case val == "":
log.Warn("empty value for 'PING'")
return false
case strings.ToUpper(val) != "PONG":
log.Warn("PING != PONG")
return false
}
log.Debugf("got: 'PING' = '%v'", val)
return true
}
func getValueFromRedisServer(key string) (string, bool) {
log.Debugf("getting '%v' from Redis server", key)
if !connectToRedisServer() {
log.Error("could not connect with Redis server")
return "", false
}
val, err := rdb.Get(rdb.Context(), key).Result()
switch {
case err == redis.Nil:
log.Errorf("key does not exist [%v]", key)
return val, false
case err != nil:
log.Errorf("get call failed for '%v'! %v", key, err.Error())
return val, false
case val == "":
log.Errorf("empty value for '%v'", key)
return val, false
}
log.Debugf("got: [%v = %v]", key, val)
return val, true
}