-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
280 lines (252 loc) · 7.1 KB
/
main.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package main
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
type RedisEnv struct {
redisAddrs string
redisMode string
redisSentinelName string
redisUsername string
redisPassword string
redisMaxConnections string
redisDBIndex string
}
type RedisClientMetadata struct {
clientType string
clusterClient *redis.ClusterClient
commonClient *redis.Client
}
func getEnv(key, defaultValue string) string {
value := os.Getenv(key)
if len(value) == 0 {
return defaultValue
}
return value
}
func splitString(input string, delimiter string) []string {
return strings.Split(input, delimiter)
}
func replaceString(input string, old string, new string) string {
return strings.ReplaceAll(input, old, new)
}
func getRedisEnv() RedisEnv {
redisAddrs := getEnv("REDIS_ADDRS", "redis://localhost:6379")
redisMode := getEnv("REDIS_MODE", "cluster")
redisSentinelName := getEnv("REDIS_SENTINEL_NAME", "mymaster")
redisUsername := getEnv("REDIS_USER", "")
redisPassword := getEnv("REDIS_PASSWORD", "")
redisMaxConnections := getEnv("REDIS_MAX_CONNECTIONS", "1000")
redisDBIndex := getEnv("REDIS_DB", "0")
return RedisEnv{
redisAddrs: redisAddrs,
redisMode: redisMode,
redisSentinelName: redisSentinelName,
redisUsername: redisUsername,
redisPassword: redisPassword,
redisMaxConnections: redisMaxConnections,
redisDBIndex: redisDBIndex,
}
}
func connectToCluster() RedisClientMetadata {
redisEnv := getRedisEnv()
redisAddrs := replaceString(redisEnv.redisAddrs, "redis://", "")
fmt.Println("redisAddrs", redisAddrs)
clusterClient := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: splitString(redisAddrs, ","),
Username: redisEnv.redisUsername,
Password: redisEnv.redisPassword,
})
ctx := context.Background()
_, err := clusterClient.Ping(ctx).Result()
if err != nil {
panic(err)
}
return RedisClientMetadata{
clientType: "cluster",
clusterClient: clusterClient,
}
}
func connectToSentinel() RedisClientMetadata {
redisEnv := getRedisEnv()
redisAddrs := replaceString(redisEnv.redisAddrs, "redis://", "")
sentinelClient := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: redisEnv.redisSentinelName,
SentinelAddrs: splitString(redisAddrs, ","),
Username: redisEnv.redisUsername,
Password: redisEnv.redisPassword,
})
ctx := context.Background()
_, err := sentinelClient.Ping(ctx).Result()
if err != nil {
panic(err)
}
return RedisClientMetadata{
clientType: "sentinel",
commonClient: sentinelClient,
}
}
func connectToReplica() RedisClientMetadata {
redisEnv := getRedisEnv()
redisAddrs := replaceString(redisEnv.redisAddrs, "redis://", "")
replicaClient := redis.NewClient(&redis.Options{
Addr: redisAddrs,
Username: redisEnv.redisUsername,
Password: redisEnv.redisPassword,
})
ctx := context.Background()
_, err := replicaClient.Ping(ctx).Result()
if err != nil {
panic(err)
}
return RedisClientMetadata{
clientType: "replica",
commonClient: replicaClient,
}
}
func getRedisClientOrCluster() RedisClientMetadata {
redisMode := getRedisEnv().redisMode
if redisMode == "cluster" {
fmt.Println("Connecting to cluster")
return connectToCluster()
} else if redisMode == "sentinel" {
fmt.Println("Connecting to sentinel")
return connectToSentinel()
} else {
fmt.Println("Connecting to standalone")
return connectToReplica()
}
}
func executeCommandOnCluster(client *redis.ClusterClient, args ...interface{}) interface{} {
ctx := context.Background()
cmd := client.Do(ctx, args...)
resp, err := cmd.Result()
if err != nil {
fmt.Println(err.Error())
return nil
}
return resp
}
func executeCommandOnCommon(client *redis.Client, args ...interface{}) interface{} {
ctx := context.Background()
resp, err := client.Do(ctx, args...).Result()
if err != nil {
fmt.Println(err.Error())
return nil
}
return resp
}
func executeCommandByClientType(client RedisClientMetadata, args ...interface{}) interface{} {
if client.clientType == "cluster" {
return executeCommandOnCluster(client.clusterClient, args...)
} else {
return executeCommandOnCommon(client.commonClient, args...)
}
}
func bulk(client RedisClientMetadata, count int) {
begin := time.Now()
for i := 0; i < count; i++ {
executeCommandByClientType(client, "SET", fmt.Sprintf("foo-%d", i), fmt.Sprintf("bar-%d", i))
executeCommandByClientType(client, "GET", fmt.Sprintf("foo-%d", i))
}
elapsed := time.Since(begin).Round(time.Millisecond)
fmt.Printf("read and write %d keys in %s\n", count, elapsed)
}
func bulkRead(client RedisClientMetadata, count int) {
begin := time.Now()
for i := 0; i < count; i++ {
executeCommandByClientType(client, "GET", fmt.Sprintf("foo-%d", i))
}
elapsed := time.Since(begin).Round(time.Millisecond)
fmt.Printf("read %d keys in %s\n", count, elapsed)
}
func bulkInsert(client RedisClientMetadata, count int) {
// check progress time
begin := time.Now()
for i := 0; i < count; i++ {
executeCommandByClientType(client, "SET", fmt.Sprintf("foo-%d", i), fmt.Sprintf("bar-%d", i))
}
elapsed := time.Since(begin).Round(time.Millisecond)
fmt.Printf("inserted %d keys in %s\n", count, elapsed)
}
func userInput(prefix string) string {
var input string
fmt.Print(prefix)
reader := bufio.NewReader(os.Stdin)
input, _ = reader.ReadString('\n')
input = strings.TrimSpace(input)
return input
}
func parseInt(input string) int {
var result int
_, err := fmt.Sscanf(input, "%d", &result)
if err != nil {
return 0
}
return result
}
func screenClear() {
fmt.Print("\033[H\033[2J")
}
func printHelp() {
fmt.Println("Go Redis Playground")
fmt.Println("Commands:")
fmt.Println(" clear - clear the screen")
fmt.Println(" help - print this help message")
fmt.Println(" exit - exit the program")
fmt.Println(" bulk-insert <count>")
fmt.Println(" bulk-read <count>")
fmt.Println(" bulk <count>")
fmt.Println(" <command> <args>")
fmt.Println("Examples:")
fmt.Println(" set foo bar")
fmt.Println(" get foo")
fmt.Println(" del foo")
}
func playground(client RedisClientMetadata) {
if client.clientType == "cluster" {
defer client.clusterClient.Close()
} else {
defer client.commonClient.Close()
}
for {
input := userInput(">> ")
if len(input) == 0 {
continue
}
fields := splitString(input, " ")
var args []interface{} = make([]interface{}, len(fields))
for i, v := range fields {
args[i] = v
}
command := args[0].(string)
// argsExceptCommand := args[1:]
if command == "exit" {
break
} else if command == "help" {
printHelp()
} else if command == "clear" {
screenClear()
} else if command == "bulk" {
bulk(client, parseInt(args[1].(string)))
} else if command == "bulk-read" {
bulkRead(client, parseInt(args[1].(string)))
} else if command == "bulk-insert" {
bulkInsert(client, parseInt(args[1].(string)))
} else {
resp := executeCommandByClientType(client, args...)
fmt.Println(resp)
}
}
}
func main() {
var clientMeta RedisClientMetadata = getRedisClientOrCluster()
fmt.Println("Connected")
fmt.Println("Try 'help' for commands")
playground(clientMeta)
}