登录
首页 >  Golang >  Go问答

请求已取消:net/http 在等待连接时超出了超时限制

来源:stackoverflow

时间:2024-03-15 21:57:30 189浏览 收藏

使用 HTTP 客户端时遇到超时错误“请求已取消:net/http 在等待连接时超出了超时限制”。通过使用 `httptrace` 分析连接过程,发现错误发生在获取连接之前。客户端的 `timeout` 设置为 500 毫秒,而服务器响应时间超过此限制。需要将客户端的 `timeout` 值增加到大于服务器响应时间,以解决此问题。

问题内容

大约3~4分钟,我的日志中会出现一些错误。

net/http:等待连接时请求被取消(等待标头时超出了 client.timeout)

我尝试使用 httptrace 找出哪里需要时间。 httptrace.getconn httptrace.gotconn

我认为它在 httptrace.gotconn 之前就耗尽了时间。 所以发生了错误 等待连接时请求被取消

我的机器没问题。这是我的 netstat。

最后确认2 close_wait 7 成立 108 syn_sent 3 time_wait 43

package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net"
    "net/http"
    "net/http/httptrace"
    "os"
    "sync"
    "time"
)

var Client *http.Client = &http.Client{
    Transport: &http.Transport{
        DisableKeepAlives:true,
        Proxy: http.ProxyFromEnvironment,
        DialContext: (&net.Dialer{
            Timeout:   3 * time.Second, // 连接超时
            KeepAlive: 10 * time.Second,
            DualStack: true,
        }).DialContext,
        IdleConnTimeout:       120 * time.Second,
        ResponseHeaderTimeout: 60 * time.Second,
        ExpectContinueTimeout: 1 * time.Second,
    },
    Timeout: 500 * time.Millisecond,
}

func GenLogId() string {
    h2 := md5.New()
    rand.Seed(time.Now().Unix())
    str := fmt.Sprintf("%d%d%d", os.Getpid(), time.Now().UnixNano(), rand.Int())

    h2.Write([]byte(str))
    uniqid := hex.EncodeToString(h2.Sum(nil))

    return uniqid
}

func main() {
    var (
        wg           sync.WaitGroup
        maxParallel  int       = 50
        parallelChan chan bool = make(chan bool, maxParallel)
    )
    for {
        parallelChan <- true
        wg.Add(1)
        go func() {
            defer func() {
                wg.Done()
                <-parallelChan
            }()
            testHttp2()
        }()
    }
    wg.Wait()
}

func testHttp2() {
    url := "http://10.33.108.39:11222/index.php"
    req, _ := http.NewRequest("GET", url, nil)

    uniqId := GenLogId()
    trace := &httptrace.ClientTrace{
        GetConn: func(hostPort string) {
            fmt.Println("GetConn id:", uniqId, time.Now().UnixNano(), hostPort)
        },
        GotConn: func(connInfo httptrace.GotConnInfo) {
            fmt.Println("GotConn id:", uniqId, time.Now().UnixNano(), connInfo.Conn.LocalAddr())
        },

        ConnectStart: func(network, addr string) {
            fmt.Println("ConnectStart id:", uniqId, time.Now().UnixNano(), network, addr)
        },
        ConnectDone: func(network, addr string, err error) {
            fmt.Println("ConnectDone id:", uniqId, time.Now().UnixNano(), network, addr, err)
        },
    }
    req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
    resp, err := Client.Do(req)
    if err != nil {
        fmt.Println("err: id", uniqId, time.Now().UnixNano(), err)
        return
    }

    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        fmt.Println("error", string(body))
    }
    return
}

您可以使用我的代码进行重现。我对这个bug很困惑... 谢谢。


解决方案


您需要增加测试的客户端 timeout 值。

这意味着您的 client.timeout 值小于您的服务器响应时间,原因有很多(例如,繁忙、cpu 过载、您每秒在此处生成的许多请求……)。

这里有一个简单的方法来解释它并重新生成它:

运行此服务器(等待 2 * time.second 然后发回响应):

package main

import (
    "io"
    "log"
    "net/http"
    "time"
)

func main() {
    http.handlefunc(`/`, func(w http.responsewriter, r *http.request) {
        log.println("wait a couple of seconds ...")
        time.sleep(2 * time.second)
        io.writestring(w, `hi`)
        log.println("done.")
    })
    log.println(http.listenandserve(":8080", nil))
}

然后运行此客户端,该客户端在 1 * time.second 内超时:

package main

import (
    "io/ioutil"
    "log"
    "net/http"
    "time"
)

func main() {
    log.println("http get")
    client := &http.client{
        timeout: 1 * time.second,
    }
    r, err := client.get(`http://127.0.0.1:8080/`)
    if err != nil {
        log.fatal(err)
    }
    defer r.body.close()
    bs, err := ioutil.readall(r.body)
    if err != nil {
        log.fatal(err)
    }
    log.println("http done.")
    log.println(string(bs))
}

输出为(client.等待 headers 时超时):

2019/10/30 11:05:08 HTTP GET
2019/10/30 11:05:09 Get http://127.0.0.1:8080/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
exit status 1

注意:
您需要相应地更改这两个设置(http.transport.responseheadertimeouthttp.client.timeout)。

以上就是《请求已取消:net/http 在等待连接时超出了超时限制》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>