在Golang中重用http连接 [英] Reusing http connections in Golang
问题描述
我目前正在努力寻找在Golang中制作HTTP帖子时重用连接的方法。
我创建了一个传输和客户端,如下所示:
//创建一个新的传输和HTTP客户端
tr:=& http.Transport {}
client:=& http.Client {Transport:tr}
然后,我将这个客户端指针传入一个goroutine,它将多个帖子传递到同一个端点,如下所示:
r,err:= client.Post(url,application / json,post)
查看netstat,这似乎会导致每个帖子的新连接导致大量并发连接处于打开状态。
在这种情况下重用连接的正确方法是什么?
解决方案<在调用
Close()
之前,您应该确保读取直到响应完成。
例如
res,_:= client.Do(req)
io.Copy(ioutil.Discard,res.Body )
res.Body.Close()
确保
http .Client
connection reuse请确保做两件事:
- 直到响应完成为止(即
Body.Close()
- / li>
I'm currently struggling to find a way to reuse connections when making HTTP posts in Golang.
I've created a transport and client like so:
// Create a new transport and HTTP client tr := &http.Transport{} client := &http.Client{Transport: tr}
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)
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?
解决方案You should ensure that you read until the response is complete before calling
Close()
.e.g.
res, _ := client.Do(req) io.Copy(ioutil.Discard, res.Body) res.Body.Close()
To ensure
http.Client
connection reuse be sure to do two things:
- Read until Response is complete (i.e.
ioutil.ReadAll(resp.Body)
) - Call
Body.Close()
这篇关于在Golang中重用http连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!