40 lines
885 B
Go
40 lines
885 B
Go
package initialization
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
"wm-backend/internal/models"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func ConnectRedis(cfg models.Config) (*redis.Client, error) {
|
|
var rdb *redis.Client
|
|
var pong string
|
|
var err error
|
|
|
|
maxRetries := 10
|
|
for range maxRetries {
|
|
rdb = redis.NewClient(&redis.Options{
|
|
Addr: fmt.Sprintf("%s:%s", cfg.Cache.Host, cfg.Cache.Port),
|
|
Password: cfg.Cache.Password,
|
|
DB: 0,
|
|
})
|
|
|
|
pong, err = rdb.Ping(context.Background()).Result()
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Error connecting to Redis")
|
|
log.Error().Msg("Retrying in 5 seconds...")
|
|
time.Sleep(5 * time.Second)
|
|
continue
|
|
} else {
|
|
log.Info().Msg("CONNECTED TO REDIS:" + pong + "🥩")
|
|
return rdb, nil
|
|
}
|
|
}
|
|
|
|
return nil, fmt.Errorf("failed to connect to Redis after %d attempts: %v", maxRetries, err)
|
|
}
|