gpt4 book ai didi

go - 每个 tcp 连接上的每个 http 请求

转载 作者:数据小太阳 更新时间:2023-10-29 03:10:18 26 4
gpt4 key购买 nike

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

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

最佳答案

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

DefaultTransport is the default implementation of Transport and is used by DefaultClient. It establishes network connections as needed and caches them for reuse by subsequent calls.

可以使用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 以禁用 keep-alive 以强制每个请求使用一个 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

关于go - 每个 tcp 连接上的每个 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53182674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com