mirror of
https://github.com/serty2005/rmser.git
synced 2026-02-05 03:12:34 -06:00
start rmser
This commit is contained in:
52
internal/infrastructure/redis/client.go
Normal file
52
internal/infrastructure/redis/client.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
rdb *redis.Client
|
||||
}
|
||||
|
||||
func NewClient(addr, password string, dbIndex int) (*Client, error) {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: addr,
|
||||
Password: password,
|
||||
DB: dbIndex,
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||
return nil, fmt.Errorf("ошибка подключения к Redis: %w", err)
|
||||
}
|
||||
|
||||
return &Client{rdb: rdb}, nil
|
||||
}
|
||||
|
||||
// Set сохраняет значение (структуру) в JSON
|
||||
func (c *Client) Set(ctx context.Context, key string, value any, ttl time.Duration) error {
|
||||
bytes, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("json marshal error: %w", err)
|
||||
}
|
||||
return c.rdb.Set(ctx, key, bytes, ttl).Err()
|
||||
}
|
||||
|
||||
// Get загружает значение в переданный указатель dest
|
||||
func (c *Client) Get(ctx context.Context, key string, dest any) error {
|
||||
val, err := c.rdb.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err == redis.Nil {
|
||||
return nil // Ключ не найден, не считаем ошибкой
|
||||
}
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal([]byte(val), dest)
|
||||
}
|
||||
Reference in New Issue
Block a user