package database import ( "ai_xhs/config" "context" "fmt" "log" "time" "github.com/redis/go-redis/v9" ) var RDB *redis.Client // InitRedis 初始化Redis连接 func InitRedis() error { cfg := config.AppConfig.Redis RDB = redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), Password: cfg.Password, DB: cfg.DB, PoolSize: cfg.PoolSize, }) // 测试连接 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := RDB.Ping(ctx).Err(); err != nil { return fmt.Errorf("Redis连接失败: %w", err) } log.Printf("Redis连接成功: %s:%d (DB:%d)", cfg.Host, cfg.Port, cfg.DB) return nil } // CloseRedis 关闭Redis连接 func CloseRedis() error { if RDB != nil { return RDB.Close() } return nil }