Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Golang并发处理HTTP客户端请求示例_创想鸟

Golang并发处理HTTP客户端请求示例

Go语言通过goroutine和channel实现高并发HTTP请求,定义FetchResult结构体统一返回结果,主函数中遍历URL列表并发调用fetchURL函数,每个goroutine将结果发送到缓冲channel,主线程收集所有响应并打印状态,实现非阻塞高效并发。

golang并发处理http客户端请求示例

Go语言通过goroutine和channel提供了强大的并发支持,处理HTTP客户端请求时可以轻松实现高并发。下面是一个实用的示例,展示如何使用Golang并发发起多个HTTP请求,并高效地收集结果。

基本并发HTTP请求结构

使用goroutine并发执行HTTP请求,配合channel同步结果,避免阻塞主线程。

定义一个结果结构体来统一返回数据:

type FetchResult struct {
  URL string
  Status string
  Body []byte
  Err error
}

主函数中启动多个并发请求:

立即学习“go语言免费学习笔记(深入)”;

func main() {
  urls := []string{
    “https://httpbin.org/delay/1”,
    “https://httpbin.org/status/200”,
    “https://httpbin.org/uuid”
  }

  results := make(chan FetchResult, len(urls))

  for _, url := range urls {
    go fetchURL(url, results)
  }

  var fetched []FetchResult
  for range urls {
    result := <-results
    fetched = append(fetched, result)
  }

  close(results)
  for _, r := range fetched {
    fmt.Printf(“URL: %s, Status: %s, Error: %v\n”, r.URL, r.Status, r.Err)
  }
}

实现fetchURL函数

该函数负责实际发起HTTP请求并发送结果到channel:

WordAi WordAi

WordAI是一个AI驱动的内容重写平台

WordAi 53 查看详情 WordAi

func fetchURL(url string, ch chan
  client := &http.Client{Timeout: 10 * time.Second}
  resp, err := client.Get(url)
  if err != nil {
    ch <- FetchResult{URL: url, Err: err}
    return
  }
  defer resp.Body.Close()

  body, _ := io.ReadAll(resp.Body)
  ch <- FetchResult{
    URL: url,
    Status: resp.Status,
    Body: body,
    Err: nil,
  }
}

控制并发数量(限流)

当请求量大时,应限制最大并发数,避免系统资源耗尽。可通过带缓冲的channel实现信号量机制:

semaphore := make(chan struct{}, 5) // 最多5个并发

在循环中调用:

go func(url string) {
  semaphore <- struct{}{}
  fetchWithTimeout(url, results)
  \}(url)

添加超时和重试机制

生产环境中建议为请求设置上下文超时和简单重试逻辑:

ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, “GET”, url, nil)
client.Do(req)

可结合for循环实现最多3次重试,每次间隔递增。

基本上就这些。Go的net/http包配合goroutine让并发请求变得直观高效,合理使用channel和context能构建出稳定可靠的客户端程序。

以上就是Golang并发处理HTTP客户端请求示例的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1167037.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
百度云管家怎么卸载_百度云管家卸载教程
上一篇 2025年12月3日 00:39:44
代号MY重磅爆料:魔域世界背后竟是多元宇宙?
下一篇 2025年12月3日 00:39:49

相关推荐

发表回复

登录后才能评论
关注微信