在Go中打开多个与服务器的保持连接

huangapple go评论82阅读模式
英文:

Open multiple keep-alives to a server in Go

问题

我有一个应用程序,它会打开与几个远程服务器(我控制的)的保持连接。在超时之前,它会发送心跳数据包以保持此连接的活跃状态。

这是我创建传输的方式:

// 与服务器的保持连接
tr := &http.Transport{}
client := &http.Client{Transport: tr}

如果我使用&http.Transport{MaxIdleConnsPerHost: 2}并将其设置为大于2,那么我就能够在每个远程连接上维护多个保持连接。然而,当有并发请求需要进行时,这些额外的保持连接是由Go自动创建的,并在超时后自动终止。

我的问题是:当我初始化传输(启动Go时)时,我如何自己创建额外的保持连接,比如每个远程服务器创建5个保持连接,并保持它们的活跃状态?这将极大地加快后续请求的速度,而速度非常重要。

英文:

I have an application that opens a keep-alive to a few remote servers (that I control). It sends a heart beat packet to keep this connection alive before the timeout.

This is how I created my transport:

// Keep-alive connection to the servers
tr := &http.Transport{}
client := &http.Client{Transport: tr}

If I use &http.Transport{MaxIdleConnsPerHost: 2} and set it to > 2, then I'm able to maintain multiple keep-alives per remote connection. However, these additional keep-alives per remote server are created by Go itself when there are concurrent requests that have to be made, and terminated automatically after the timeout expires.

My question is: how can I create the additional keep-alives, say 5 keep-alives per remote server myself when I initialize my transport (when I start Go) and keep them all alive? This would speed up subsequent requests greatly and speed is very important.

答案1

得分: 1

根据go-nuts组的输入,为了手动打开多个保持连接到一个服务器,我们进行了相同数量的同时请求。然后,Go会保持这些连接直到远程服务器超时(在Apache中默认为5秒)。

请注意,这些连接不能超过默认值为2的MaxIdleConnsPerHost

您可以使用netstat -p tcp来验证这种行为。

英文:

Based on inputs from the go-nuts group, to manually open multiple keep-alives to one server, we make that many simultaneous requests. Go then keeps these alive till the remote server times them out (default 5 seconds in Apache).

Please note that these connections cannot be more than the MaxIdleConnsPerHost which is 2 by default.

You can verify this behaviour using netstat -p tcp

huangapple
  • 本文由 发表于 2014年9月10日 02:41:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/25751558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定