http - 为什么 Go HTTPS 客户端不重用连接?

标签 http go

我有一个 http 客户端,它创建到主机的多个连接。我想设置它可以设置到特定主机的最大连接数。 go 的 request.Transport 中没有这样的选项。 我的代码看起来像

package main 

import (
  "fmt"
  "net/http"
  "net/url"
)

const (
  endpoint_url_fmt      = "https://blah.com/api1?%s"
)


func main() {

  transport := http.Transport{ DisableKeepAlives : false }

  outParams := url.Values{}
  outParams.Set("method", "write")
  outParams.Set("message", "BLAH")

  for {
    // Encode as part of URI.
    outboundRequest, err := http.NewRequest(
      "GET",
      fmt.Sprintf(endpoint_url_fmt, outParams.Encode()),
      nil
    )
    outboundRequest.Close = false
    _ , err = transport.RoundTrip(outboundRequest)
    if err != nil {
      fmt.Println(err)
    }
  }

}

我希望这会创建 1 个连接。正如我在 for 循环中调用它一样。但这会不断创建无限数量的连接。

使用 requests 库的类似 python 代码只创建一个连接。

#!/usr/bin/env python
import requests
endpoint_url_fmt      = "https://something.com/restserver.php"
params = {}
params['method'] = 'write'
params['category'] = category_errors_scuba
params['message'] = "blah"
while True:
  r = requests.get(endpoint_url_fmt, params = params)

由于某种原因,go 代码没有重用 http 连接。

编辑: go 代码需要关闭 body 才能重用连接。

 resp , err = transport.RoundTrip(outboundRequest)
 resp.Close() //  This allows the connection to be reused

最佳答案

基于 OP 的进一步澄清。默认客户端确实重用连接。

一定要关闭response .

Callers should close resp.Body when done reading from it. If resp.Body is not closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request.

此外,我发现在调用 Close() 之前,我还需要阅读直到响应完成

例如

res, _ := client.Do(req)
io.Copy(ioutil.Discard, res.Body)
res.Body.Close()

为确保 http.Client 连接重用,请务必做两件事:

  • 读取直到响应完成(即 ioutil.ReadAll(resp.Body))
  • 调用Body.Close()

旧答案,对速率限制有用,但不是 OP 所追求的:

我认为通过 golang 1.1 http API 设置最大连接数是不可能的。这意味着如果您不小心,您可能会因大量 TCP 连接而自责(直到您用完文件描述符或其他任何东西)。

也就是说,您可以通过 time.Tick 限制为特定主机(以及因此出站请求和连接)调用 go 例程的速率

例如:

import "time"

requests_per_second := 5
throttle := time.Tick(1000000000 / requests_per_second)

for i := 0; i < 16; i += 1 {
  <-throttle  
  go serveQueue()
}

关于http - 为什么 Go HTTPS 客户端不重用连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17959732/

相关文章:

android - 网络绑定(bind)不适用于 jni 代码吗?

security - HTTP是否重定向到密码的HTTPS风险捕获?

c# - 从 HttpWebRequest 和 HttpWebResponse 获取 Http 状态代码(200、301、404 等)

json - 如果逻辑应用程序不为空,则返回 JSON 字段

go - 如何处理范围的并发映射

Go:获取两个极限之间的所有数字/字母范围

http - 204 无响应应该使用什么内容类型?

Python Spotify OAuth 流程

go - 嵌入式类型的类型断言

http - Go - 运行时错误 : invalid memory address or nil pointer dereference