package database import ( "context" "encoding/json" "fmt" "time" "dd_fiber_api/config" "github.com/redis/go-redis/v9" ) // RedisClient Redis客户端 type RedisClient struct { rdb *redis.Client } // NewRedisClient 创建Redis客户端 func NewRedisClient(cfg *config.RedisConfig) (*RedisClient, error) { rdb := redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), Password: cfg.Password, DB: cfg.DB, PoolSize: cfg.PoolSize, MinIdleConns: cfg.MinIdleConns, }) // 测试连接 ctx := context.Background() if err := rdb.Ping(ctx).Err(); err != nil { return nil, fmt.Errorf("Redis连接失败: %w", err) } return &RedisClient{rdb: rdb}, nil } // Ping 测试Redis连接 func (c *RedisClient) Ping(ctx context.Context) error { return c.rdb.Ping(ctx).Err() } // Set 设置键值对,带过期时间 func (c *RedisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error { jsonData, err := json.Marshal(value) if err != nil { return fmt.Errorf("序列化数据失败: %w", err) } return c.rdb.Set(ctx, key, jsonData, expiration).Err() } // Get 获取键值对 func (c *RedisClient) Get(ctx context.Context, key string, dest interface{}) error { val, err := c.rdb.Get(ctx, key).Result() if err != nil { if err == redis.Nil { return fmt.Errorf("键不存在: %s", key) } return fmt.Errorf("获取键值失败: %w", err) } if err := json.Unmarshal([]byte(val), dest); err != nil { return fmt.Errorf("反序列化数据失败: %w", err) } return nil } // Exists 检查键是否存在 func (c *RedisClient) Exists(ctx context.Context, key string) (bool, error) { count, err := c.rdb.Exists(ctx, key).Result() if err != nil { return false, fmt.Errorf("检查键存在性失败: %w", err) } return count > 0, nil } // Delete 删除键 func (c *RedisClient) Delete(ctx context.Context, key string) error { return c.rdb.Del(ctx, key).Err() } // Close 关闭Redis连接 func (c *RedisClient) Close() error { return c.rdb.Close() }