start rmser

This commit is contained in:
2025-11-29 08:40:24 +03:00
commit 5aa2238eea
2117 changed files with 375169 additions and 0 deletions

View 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)
}