46 lines
869 B
Go
46 lines
869 B
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
type Redis struct {
|
|
Client *redis.Client
|
|
logger *zap.Logger
|
|
}
|
|
|
|
func NewRedis(ctx context.Context, uri string, logger *zap.Logger) (*Redis, error) {
|
|
if uri == "" {
|
|
return nil, fmt.Errorf("redis URI is empty")
|
|
}
|
|
|
|
opts, err := redis.ParseURL(uri)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("redis parse URL: %w", err)
|
|
}
|
|
|
|
client := redis.NewClient(opts)
|
|
|
|
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if err := client.Ping(pingCtx).Err(); err != nil {
|
|
_ = client.Close()
|
|
return nil, fmt.Errorf("redis ping: %w", err)
|
|
}
|
|
|
|
logger.Info("connected to Redis")
|
|
return &Redis{Client: client, logger: logger}, nil
|
|
}
|
|
|
|
func (r *Redis) Close() error {
|
|
if r == nil || r.Client == nil {
|
|
return nil
|
|
}
|
|
return r.Client.Close()
|
|
}
|