HTTP长连接请求时间长,客户端会超时吗?

Will client timeout if a request on HTTP persistent connection takes a long time?

如果我们有一个 HTTP 持久连接,但是其中一个请求需要很长时间(比如 30 秒)。 假设客户端超时为 15 秒。

  1. 在持久连接上使用时是否遵守客户端的请求超时?

  2. 如果是,那么连接是否断开?

  3. 有没有办法避免整个连接中断,而只是在那个特定请求上超时?

  1. 客户端可以指定超时时间,但这取决于使用客户端超时的服务器配置或它自己的超时配置。默认情况下,服务器端超时配置的优先级高于客户端超时配置。
  2. 没有
  3. 对于具有不同超时配置的特定请求,在同一连接上是不可能的但是,您可以声明不同的 http 客户端配置连接,并将其中一个用于默认值,另一个用于需要更多超时值的请求但是它们不在同一个 keep-alive 连接中。
    注意,在客户端超时配置中,我们有两种不同类型的超时
    1- 打开连接超时 2- 读取响应超时。
    第一个声明用于服务器和客户端之间的打开连接,第二个声明声明客户端需要多长时间才能获得对其请求的响应。

这取决于您使用的客户端以及服务器的配置方式。问题更复杂......在http中设置keep-alive不会避免传输级别的tcp超时,你需要将tcp超时设置为keep-alive同样,但是服务器可能不想为您保持连接,只要您愿意。对于持久连接,最好使用 udp 而不是 tcp - 它没有如此严格的流量控制。另一件事是 HTTP/2 根本没有 keep-alive 这样的东西,因为事情的处理方式与 HTTP/1 完全不同。来自 HTTP/2 RFC:

8.1.2.2. Connection-Specific Header Fields

HTTP/2 does not use the Connection header field to indicate
connection-specific header fields; in this protocol, connection-
specific metadata is conveyed by other means. An endpoint MUST NOT
generate an HTTP/2 message containing connection-specific header
fields; any message containing connection-specific header fields MUST be treated as malformed (Section 8.1.2.6).

The only exception to this is the TE header field, which MAY be
present in an HTTP/2 request; when it is, it MUST NOT contain any
value other than "trailers".

This means that an intermediary transforming an HTTP/1.x message to HTTP/2 will need to remove any header fields nominated by the
Connection header field, along with the Connection header field
itself. Such intermediaries SHOULD also remove other connection-
specific header fields, such as Keep-Alive, Proxy-Connection,
Transfer-Encoding, and Upgrade, even if they are not nominated by the Connection header field.