通八洲科技

如何使用Golang实现并发HTTP请求_同时获取多个接口数据

日期:2026-01-02 00:00 / 作者:P粉602998670
Go 并发 HTTP 请求需控制并发数(20–50)、使用 context 统一超时、通过 channel 安全收集结果;避免盲目启大量 goroutine,推荐 semaphore 或带缓冲 channel 限流,并用结构体封装结果防止竞态。

用 Go 实现并发 HTTP 请求,核心是结合 goroutinechannel 控制并发流程,同时避免资源耗尽和超时堆积。关键不是“越多越快”,而是合理控制并发数、统一处理错误与超时、安全收集结果。

控制并发数量,防止压垮服务或自身

直接为每个请求起一个 goroutine 容易失控(比如 1000 个 URL 启 1000 个 goroutine),推荐使用带缓冲的 channel 或 semaphore 模式限制并发数:

每个请求必须带上下文(context)超时

单个请求卡住会拖慢整个批次。务必用 context.WithTimeoutcontext.WithDeadline 包裹请求:

用 channel 安全收集结果,区分成功与失败

避免多个 goroutine 写同一 slice 引发竞态。建议定义结构体封装结果,并用 channel 统一接收:

type Result struct {
    URL     string
    Data    []byte
    Err     error
    Status  int
}

完整轻量示例(无依赖,开箱即用)

以下代码并发请求 3 个 URL,最大并发 2,每请求 3 秒超时:

func fetchURL(ctx context.Context, url string, sem chan struct{}) Result {
    sem <- struct{}{} // 获取令牌
    defer func() { <-sem }() // 释放令牌
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Do(req)
if err != nil {
    return Result{URL: url, Err: err}
}
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
return Result{URL: url, Data: data, Status: resp.StatusCode}

}

func main() { urls := []string{"https://www./link/5f69e19efaba426d62faeab93c308f5c", "https://www./link/ef246753a70fce661e16668898810624", "https://www./link/8c4b0479f20772cb9b68cf5f161d1e6f"} sem := make(chan struct{}, 2) ch := make(chan Result, len(urls))

for _, u := range urls {
    go func(url string) {
        ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
        defer cancel()
        ch <- fetchURL(ctx, url, sem)
    }(u)
}

results := make([]Result, 0, len(urls))
for i := 0; i < len(urls); i++ {
    results = append(results, <-ch)
}

for _, r := range results {
    if r.Err != nil {
        fmt.Printf("❌ %s → %v\n", r.URL, r.Err)
    } else {
        fmt.Printf("✅ %s → %d bytes, status %d\n", r.URL, len(r.Data), r.Status)
    }
}

}

不复杂但容易忽略细节:限流、上下文、结果收集三者缺一不可。实际项目中可进一步封装成可复用函数,支持自定义 Header、重试、熔断等。