猿问

为什么 Go HTTPS Client 不重用连接?

我有一个 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 循环中调用它时。但这会不断创建无限数量的连接。


使用请求库的类似 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 代码需要关闭主体以重用连接。


 resp , err = transport.RoundTrip(outboundRequest)

 resp.Close() //  This allows the connection to be reused


慕村9548890
浏览 243回答 2
2回答

摇曳的蔷薇

有一些有趣的改进http.Transport:// 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// ...// MaxIdleConns controls the maximum number of idle (keep-alive)// connections across all hosts. Zero means no limit.MaxIdleConns int // Go 1.7// MaxIdleConnsPerHost, if non-zero, controls the maximum idle// (keep-alive) connections to keep per-host. If zero,// DefaultMaxIdleConnsPerHost is used.MaxIdleConnsPerHost int// 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.MaxConnsPerHost int // Go 1.11
随时随地看视频慕课网APP

相关分类

Go
我要回答