为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕村9548890 2021-06-08 13:15:04
我有一个 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 pythonimport requestsendpoint_url_fmt      = "https://something.com/restserver.php"params = {}params['method'] = 'write'params['category'] = category_errors_scubaparams['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
查看完整描述

2 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

有一些有趣的改进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


查看完整回答
反对 回复 2021-06-21
  • 2 回答
  • 0 关注
  • 242 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信