2024-02-15 15:17:57 +01:00
|
|
|
package setup
|
|
|
|
|
|
|
|
import (
|
2024-09-23 15:16:30 +02:00
|
|
|
"context"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
2024-02-15 15:17:57 +01:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"forge.cadoles.com/cadoles/bouncer/internal/config"
|
2024-09-23 15:16:30 +02:00
|
|
|
"github.com/pkg/errors"
|
2024-02-15 15:17:57 +01:00
|
|
|
"github.com/redis/go-redis/v9"
|
2024-09-23 15:16:30 +02:00
|
|
|
"gitlab.com/wpetit/goweb/logger"
|
2024-02-15 15:17:57 +01:00
|
|
|
)
|
|
|
|
|
2024-09-23 15:16:30 +02:00
|
|
|
var clients sync.Map
|
|
|
|
|
|
|
|
func NewSharedClient(conf config.RedisConfig) redis.UniversalClient {
|
|
|
|
key := strings.Join(conf.Adresses, "|") + "|" + string(conf.Master)
|
|
|
|
|
|
|
|
value, exists := clients.Load(key)
|
|
|
|
if exists {
|
|
|
|
if client, ok := (value).(redis.UniversalClient); ok {
|
|
|
|
return client
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
client := newRedisClient(conf)
|
|
|
|
|
|
|
|
clients.Store(key, client)
|
|
|
|
|
|
|
|
return client
|
|
|
|
}
|
|
|
|
|
2024-02-15 15:17:57 +01:00
|
|
|
func newRedisClient(conf config.RedisConfig) redis.UniversalClient {
|
2024-09-23 15:16:30 +02:00
|
|
|
client := redis.NewUniversalClient(&redis.UniversalOptions{
|
2024-02-15 15:17:57 +01:00
|
|
|
Addrs: conf.Adresses,
|
|
|
|
MasterName: string(conf.Master),
|
|
|
|
ReadTimeout: time.Duration(conf.ReadTimeout),
|
|
|
|
WriteTimeout: time.Duration(conf.WriteTimeout),
|
|
|
|
DialTimeout: time.Duration(conf.DialTimeout),
|
|
|
|
RouteByLatency: true,
|
|
|
|
ContextTimeoutEnabled: true,
|
2024-09-23 15:16:30 +02:00
|
|
|
MaxRetries: int(conf.MaxRetries),
|
2024-02-15 15:17:57 +01:00
|
|
|
})
|
2024-09-23 15:16:30 +02:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
ctx := logger.With(context.Background(),
|
|
|
|
logger.F("adresses", conf.Adresses),
|
|
|
|
logger.F("master", conf.Master),
|
|
|
|
)
|
|
|
|
|
|
|
|
timer := time.NewTicker(time.Duration(conf.PingInterval))
|
|
|
|
defer timer.Stop()
|
|
|
|
|
|
|
|
connected := true
|
|
|
|
|
|
|
|
for range timer.C {
|
|
|
|
if _, err := client.Ping(ctx).Result(); err != nil {
|
2024-09-27 10:15:08 +02:00
|
|
|
logger.Error(ctx, "redis disconnected", logger.CapturedE(errors.WithStack(err)))
|
2024-09-23 15:16:30 +02:00
|
|
|
connected = false
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if !connected {
|
|
|
|
logger.Info(ctx, "redis reconnected")
|
|
|
|
connected = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return client
|
2024-02-15 15:17:57 +01:00
|
|
|
}
|