Golang HTTP 并发请求 POST EOF

nem*_*emo 6 http go web

我在 Go 中运行一个小客户端。目前我们收到了许多误报,这似乎归结为client.Do()num>=1000.

这是我的代码的本质:

func DoCreate(js string, cli *http.Client) {

    url2 := "http://xvz.myserver.com:9000/path/create"

    postBytesReader := bytes.NewReader([]byte(js))
    request, _ := http.NewRequest("POST", url2, postBytesReader)

    resp, err := cli.Do(request)
    if err != nil {
        fmt.Println(err) // Post http://xvz.myserver.com:9000/path/create: EOF 
        return
    }
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))

    defer resp.Body.Close()
}

func main() {
    client := &http.Client{
        CheckRedirect: nil,
    }

    for i := 0; i < num; i++ {
        var pq CreateReqInfo
        pq.Uid = strconv.Itoa(bid + i)
        petstr, _ := json.Marshal(pq)
        go DoCreate(string(petstr), client)
    }
}
Run Code Online (Sandbox Code Playgroud)

文件句柄数或最大连接数有问题吗?

jet*_*eon 14

在我看来,您可能遇到了此答案中描述的问题。基本上,Go http 客户端将尝试重用连接,除非您明确指出它不应该在Transport您已将Client实例设置为使用或在请求本身中使用:

request.Close = true
Run Code Online (Sandbox Code Playgroud)

当另一端的服务器关闭连接而没有Connection: close在响应中使用标头指示时,这就会成为一个问题。该net.http代码假定连接仍处于打开状态,因此下一个尝试使用该连接的请求会EOF在另一次关闭连接时遇到。

您需要检查第 1000 个请求前后的连接发生了什么。接收服务器是否设置为限制每个客户端的连接数?您的代码是否遇到连接超时?在任何一种情况下,如果发生这种情况,服务器以 GoClient代码无法预测的方式关闭了连接,那么您将遇到EOF.