美文网首页
关于http keep-alive 2022-04-10

关于http keep-alive 2022-04-10

作者: 9_SooHyun | 来源:发表于2022-04-09 17:01 被阅读0次

TCP的keepalive和HTTP的keep-alive

  • TCP keepalive是用来检测保活的
  • HTTP keep-alive 是用来设置生效(开关)的,即是否复用TCP链接。不复用则服务端会主动断掉tcp链接,从而断掉上层的http链接

HTTP connection:keep-Alive机制,并非无限期的维持TCP,长时间的TCP连接维持,会一定程度的浪费系统资源。默认情况下,距离上一次请求结束10秒(可配置)内无任何请求,服务端会主动断掉TCP连接
TCP的keepAlive,系统级默认是2+小时

参考https://segmentfault.com/a/1190000012894416

关于http连续请求可能读到EOF的问题

使用golang标准库net/http很可能就会碰上这个问题
根本原因是 http.client拿出一个已经关闭的连接进行复用导致出错

Go by default will send requests with the header Connection: Keep-Alive and persist connections for re-use. The problem is that the server is responding with Connection: Keep-Alive in the response header, but then 【immediately closing the connection】.

As a little background as to how go implements connections in this case (you can look at the full code in net/http/transport.go). There are two goroutines, one responsible for writing and one responsible for reading (readLoop and writeLoop) In most circumstances readLoop will detect a close on the socket, and close down the connection. The problem here occurs when you initiate another request before the readLoop actually detects the close, and the EOF that it reads get interpreted as an error for that new request rather than a close that occurred prior to the request.

如果server端不支持长链接,那么为了避免连续的多个请求读到EOF,应当主动使用http短链接(in golang net/http, set req.Close to true)

client := &http.Client{}
req, err := http.NewRequest(method, url, httpBody)

// NOTE this !!
req.Close = true

req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth("user", "pass")
resp, err := client.Do(req)
if err != nil {
    // whatever
}
defer resp.Body.Close()

response, err = ioutil.ReadAll(resp.Body)
if err != nil {
    // Whatever
}

参考:
https://juejin.cn/post/6997294512053878821
https://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors-when-making-multiple-requests-successi

相关文章

网友评论

      本文标题:关于http keep-alive 2022-04-10

      本文链接:https://www.haomeiwen.com/subject/bewvsrtx.html