3 回答

TA貢獻1779條經(jīng)驗 獲得超6個贊
連接被添加到函數(shù)Transport.tryPutIdleConn中的池中。如果Transport.DisableKeepAlives為 true 或?Transport.MaxIdleConnsPerHost小于零,則不會合并連接。
設(shè)置任一值都會禁用池化。Connection: close
當DisableKeepAlives 為true 時,傳輸會添加請求標頭。這可能是理想的,也可能不是理想的,具體取決于您正在測試的內(nèi)容。
設(shè)置DisableKeepAlives的方法如下:
t?:=?http.DefaultTransport.(*http.Transport).Clone() t.DisableKeepAlives?=?true c?:=?&http.Client{Transport:?t}
在操場上運行DisableKeepAlives = true 的演示。
設(shè)置 MaxIdleConnsPerHost 的方法如下:
t?:=?http.DefaultTransport.(*http.Transport).Clone() t.MaxIdleConnsPerHost?=?-1 c?:=?&http.Client{Transport:?t}
在操場上運行 MaxIdleConnsPerHost = -1 的演示。
上面的代碼克隆了默認傳輸以確保使用默認傳輸選項。如果您明確想要問題中的選項,請使用
????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, ????????????DisableKeepAlives:?true, ????????}, ????}
或者
????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, ????????????MaxIdleConnsPerHost:?-1, ????????}, ????}
MaxIdleConnsPerHost 不限制每個主機的活動連接數(shù)。?
通過將Dialer.KeepAlive設(shè)置為 -1,不會禁用池 。

TA貢獻1951條經(jīng)驗 獲得超3個贊
您需要將DisableKeepAlives、true和MaxIdleConnsPerHost-1 設(shè)置為。
從文檔中:
// DisableKeepAlives, if true, disables HTTP keep-alives and
// will only use the connection to the server for a single
// HTTP request.
https://golang.org/src/net/http/transport.go,第 166 和 187 行
因此,您的客戶端必須按如下方式初始化
c = &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DisableKeepAlives: true,
MaxIdleConnsPerHost: -1
},
}
如果您使用 1.7 之前的 Go 版本,那么您需要消耗主體的所有緩沖區(qū),并且只有在調(diào)用request.Body.Close(). 相反,如果您使用的版本大于或等于 1.7,則可以推遲關(guān)閉,而無需采取額外的預防措施。
禁用連接池但仍然能夠執(zhí)行并行請求的示例庫: https: //github.com/alessiosavi/Requests

TA貢獻1842條經(jīng)驗 獲得超13個贊
http.Transport 有一個名為MaxConnsPerHost
MaxConnsPerHost 可以選擇限制每個主機的連接總數(shù),包括處于撥號、活動和空閑狀態(tài)的連接。
包括撥號、活動和空閑狀態(tài)
- 3 回答
- 0 關(guān)注
- 208 瀏覽
添加回答
舉報