-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathredis-connect.go
55 lines (45 loc) · 1.12 KB
/
redis-connect.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
package main
import (
"context"
"fmt"
"github.com/cenkalti/backoff/v4"
"log"
"time"
"github.com/redis/go-redis/v9"
)
type RedisConfig struct {
Host string
Port string
Password string
User string
}
// Connect to Redis and return a Redis client.
// Wait for the connection to be established before returning.
func connectToRedis(conf RedisConfig) *redis.Client {
bf := backoff.NewExponentialBackOff()
bf.InitialInterval = 10 * time.Second
bf.MaxInterval = 25 * time.Second
bf.MaxElapsedTime = 90 * time.Second
rdb, err := backoff.RetryWithData[*redis.Client](func() (*redis.Client, error) {
ctx, cancel := context.WithTimeout(context.Background(), bf.InitialInterval)
defer cancel()
conn := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", conf.Host, conf.Port),
Password: conf.Password,
Username: conf.User,
DB: 0,
})
_, err := conn.Ping(ctx).Result()
if err != nil {
log.Println("Redis not yet ready...")
return nil, err
}
log.Println("Connected to Redis!")
return conn, nil
}, bf)
if err != nil {
log.Fatalln(err)
return nil
}
return rdb
}