在 Go 中重用 http 连接 [英] Reusing http connections in Go

查看:29
本文介绍了在 Go 中重用 http 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在努力寻找一种在 Go 中创建 HTTP 帖子时重用连接的方法.

I'm currently struggling to find a way to reuse connections when making HTTP posts in Go.

我已经创建了一个像这样的传输和客户端:

I've created a transport and client like so:

// Create a new transport and HTTP client
tr := &http.Transport{}
client := &http.Client{Transport: tr}

然后我将此客户端指针传递到一个 goroutine 中,该 goroutine 向同一个端点发送多个帖子,如下所示:

I'm then passing this client pointer into a goroutine which is making multiple posts to the same endpoint like so:

r, err := client.Post(url, "application/json", post)

查看 netstat 这似乎导致每个帖子都有一个新连接,从而导致大量并发连接被打开.

Looking at netstat this appears to be resulting in a new connection for every post resulting in a large number of concurrent connections being open.

在这种情况下重用连接的正确方法是什么?

What is the correct way to reuse connections in this case?

推荐答案

确保您阅读直到响应完成并调用 Close().

例如

res, _ := client.Do(req)
io.Copy(ioutil.Discard, res.Body)
res.Body.Close()

再次...要确保 http.Client 连接重用,请务必:

Again... To ensure http.Client connection reuse be sure to:

  • 阅读直到响应完成(即ioutil.ReadAll(resp.Body))
  • 调用Body.Close()

这篇关于在 Go 中重用 http 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆