通过每个TCP连接的每个HTTP请求

时间:2018-11-07 01:58:03

标签: go

我的问题很简单:Go中有多少个HTTP请求建立了到服务器的tcp连接。

我正在编码一个可以发送许多http请求的工具,但是我发现所有这些请求都是通过一个或两个tcp连接实现的,好像golang http Transport有一个连接池。

1 个答案:

答案 0 :(得分:1)

如果您将DefaultTransport用于HTTP请求,则将重新使用TCP连接。

  

DefaultTransport是Transport的默认实现,由DefaultClient使用。它根据需要建立网络连接,并缓存它们以供后续调用重用。

您可以使用MaxConnsPerHost限制连接总数:

// MaxConnsPerHost optionally limits the total number of
// connections per host, including connections in the dialing,
// active, and idle states. On limit violation, dials will block.
//
// Zero means no limit.
//
// For HTTP/2, this currently only controls the number of new
// connections being created at a time, instead of the total
// number. In practice, hosts using HTTP/2 only have about one
// idle connection, though.
MaxConnsPerHost int

修改

我强烈建议您阅读docs,因为Go拥有最有据可查的标准库之一。无论如何,您可以将http.Transport配置为禁用保持活动状态,以强制每个请求使用一个TCP连接。

// DisableKeepAlives, if true, disables HTTP keep-alives and
// will only use the connection to the server for a single
// HTTP request.
//
// This is unrelated to the similarly named TCP keep-alives.
DisableKeepAlives bool