dcbot/cmd/dcbot/internal/redis.go

42 lines
869 B
Go

package internal
import (
"context"
"fmt"
"time"
"github.com/kelseyhightower/envconfig"
"github.com/redis/go-redis/v9"
)
const (
redisPingTimeout = 10 * time.Second
)
type redisConfig struct {
ConnectionString string `envconfig:"CONNECTION_STRING" required:"true"`
}
func NewRedisClient() (*redis.Client, error) {
var cfg redisConfig
if err := envconfig.Process("REDIS", &cfg); err != nil {
return nil, fmt.Errorf("envconfig.Process: %w", err)
}
opts, err := redis.ParseURL(cfg.ConnectionString)
if err != nil {
return nil, fmt.Errorf("couldn't parse REDIS_CONNECTION_STRING: %w", err)
}
c := redis.NewClient(opts)
ctx, cancel := context.WithTimeout(context.Background(), redisPingTimeout)
defer cancel()
if err = c.Ping(ctx).Err(); err != nil {
_ = c.Close()
return nil, fmt.Errorf("couldn't ping redis: %w", err)
}
return c, nil
}