net/http.Client
,并禁用连接池。我的目标是,在每个HTTP/1.x请求时,都会建立到地址的新TCP连接。目前我有:
c = &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 5 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
有什么建议可以调整这个吗?
我发现如果设置c.Transport.MaxIdleConns = 1
,可能会起作用,但我不确定这是否仍允许使用1个+1个空闲(共2个)TCP连接:
// MaxIdleConns controls the maximum number of idle (keep-alive)
// connections across all hosts. Zero means no limit.
MaxIdleConns int
同样地,c.Dialer.KeepAlive = -1
似乎也能实现这个目的:
// KeepAlive specifies the keep-alive period for an active
// network connection.
// If zero, keep-alives are enabled if supported by the protocol
// and operating system. Network protocols or operating systems
// that do not support keep-alives ignore this field.
// If negative, keep-alives are disabled.
但我不确定TCP连接+ Keep-Alive + HTTP的行为。
另一种方法是尽快终止空闲的TCP连接,因此我设置了c.Transport.IdleConnTimeout = 1*time.Nanosecond
。
当我这样做时,我的Client.Do()
现在偶尔会返回错误:
tls: use of closed connection
我怀疑这是 Go 标准库的问题(可能是竞争条件),它使用了一个应该已经从池中取出的连接。
Request.Close
(或设置Connection: close
标头)吗? - JimB