【发布时间】:2019-08-27 22:55:27
【问题描述】:
出于测试目的,我尝试在 Go 中创建一个禁用连接池的 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 stdlib 问题(可能是一场比赛),它使用了一个应该从池中取出的连接。
【问题讨论】:
-
您只需要一个客户吗?最直接的方法是简单地使用一个函数,该函数返回一个您可以使用的新客户端对象。
-
@Jesse,如果你只这样做,那么你将泄漏打开的 tcp 连接
-
为什么不直接关闭连接,而不用担心池?您是否尝试过使用
Request.Close(或设置Connection: close标头)? -
@JimB 如果是出于测试目的,那可能不是问题。
-
这些都可以。介意添加作为答案吗?
标签: go