Files
uptimesebi/internal/platform/redis.go
T

55 lines
1.2 KiB
Go

package platform
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
)
func OpenRedis(ctx context.Context, c config.Common) (*redis.Client, error) {
var rdb *redis.Client
if c.RedisSentinel.Enabled() {
opts, err := failoverOptions(c.RedisURL, c.RedisSentinel)
if err != nil {
return nil, fmt.Errorf("redis: %w", err)
}
rdb = redis.NewFailoverClient(opts)
} else {
opts, err := redis.ParseURL(c.RedisURL)
if err != nil {
return nil, fmt.Errorf("redis: %w", err)
}
rdb = redis.NewClient(opts)
}
if err := rdb.Ping(ctx).Err(); err != nil {
_ = rdb.Close()
return nil, fmt.Errorf("redis: %w", err)
}
return rdb, nil
}
func failoverOptions(url string, s config.Sentinel) (*redis.FailoverOptions, error) {
fo := &redis.FailoverOptions{
MasterName: s.Master,
SentinelAddrs: s.Addrs,
SentinelUsername: s.Username,
SentinelPassword: s.Password,
}
if url == "" {
return fo, nil
}
base, err := redis.ParseURL(url)
if err != nil {
return nil, err
}
fo.Username = base.Username
fo.Password = base.Password
fo.DB = base.DB
fo.TLSConfig = base.TLSConfig
fo.Protocol = base.Protocol
return fo, nil
}