使用连接重用的响应排序
🌐 Response ordering with connection reuse
在复用的 HTTP/1.1 keep-alive 连接上,响应是按它们在该连接上的顺序与请求相关联的。HTTP/1.1 keep-alive 不提供超出顺序之外的每个请求的响应归属。需要每个请求独立连接的应用可以使用单独的 Agent,禁用 keep-alive,或者传递 agent: false。
🌐 On a reused HTTP/1.1 keep-alive connection, responses are associated with
requests by their order on that connection. HTTP/1.1 keep-alive does not provide
per-request response attribution beyond that ordering. Applications that require
per-request connection isolation can use a separate Agent, disable keep-alive,
or pass agent: false.
当连接被客户端或服务器关闭时,它将从连接池中移除。连接池中任何未使用的套接字都会被取消引用,以便在没有未完成请求时不会保持 Node.js 进程运行。(参见 socket.unref())。
🌐 When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see socket.unref()).
在不再使用 Agent 实例时释放它是一个好习惯,因为未使用的套接字会消耗操作系统资源。
🌐 It is good practice, to destroy() an Agent instance when it is no
longer in use, because unused sockets consume OS resources.
当套接字触发 'close' 事件或 'agentRemove' 事件时,该套接字会从代理中移除。如果打算在不将 HTTP 请求保留在代理中的情况下长时间保持一个 HTTP 请求,可以像下面这样做:
🌐 Sockets are removed from an agent when the socket emits either
a 'close' event or an 'agentRemove' event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
http.get(options, (res) => {
// Do stuff
}).on('socket', (socket) => {
socket.emit('agentRemove');
}); 代理也可以用于单独的请求。通过向 http.get() 或 http.request() 函数提供 {agent: false} 作为选项,将使用具有默认选项的一次性 Agent 来处理客户端连接。
🌐 An agent may also be used for an individual request. By providing
{agent: false} as an option to the http.get() or http.request()
functions, a one-time use Agent with default options will be used
for the client connection.
agent:false:
http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false, // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
}); 使用 agent: false 来避免请求的连接重用。
🌐 Use agent: false to avoid connection reuse for a request.