Files
moteva/server/internal/infrastructure/cache/redis_store.go
T

58 lines
1.2 KiB
Go
Raw Normal View History

package cache
import (
"context"
"encoding/json"
"time"
"github.com/redis/go-redis/v9"
)
type RedisOptions struct {
Addr string
Password string
DB int
}
type RedisStore struct {
client *redis.Client
}
func NewRedisStore(ctx context.Context, opts RedisOptions) (*RedisStore, error) {
client := redis.NewClient(&redis.Options{
Addr: opts.Addr,
Password: opts.Password,
DB: opts.DB,
})
if err := client.Ping(ctx).Err(); err != nil {
return nil, err
}
return &RedisStore{client: client}, nil
}
func (s *RedisStore) Get(ctx context.Context, key string, target any) (bool, error) {
value, err := s.client.Get(ctx, key).Bytes()
if err != nil {
if err == redis.Nil {
return false, nil
}
return false, err
}
if err := json.Unmarshal(value, target); err != nil {
return false, err
}
return true, nil
}
func (s *RedisStore) Set(ctx context.Context, key string, value any, ttl time.Duration) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
return s.client.Set(ctx, key, data, ttl).Err()
}
func (s *RedisStore) Delete(ctx context.Context, key string) error {
return s.client.Del(ctx, key).Err()
}