类:http.Agent
【Class: http.Agent】
Agent 负责管理 HTTP 客户端的连接持久性和重用。它维护一个针对特定主机和端口的待处理请求队列,为每个请求队列复用单个套接字连接,直到队列为空,此时套接字要么被销毁,要么被放入池中,以便再次用于对相同主机和端口的请求。套接字是被销毁还是放入池中取决于 keepAlive 选项。
【An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
keepAlive option.】
连接池中的连接已启用 TCP Keep-Alive,但服务器仍可能关闭空闲连接,在这种情况下,它们将被从连接池中移除,并且在对该主机和端口发起新的 HTTP 请求时会建立新的连接。服务器也可能拒绝在同一连接上处理多个请求,那么每个请求都必须重新建立连接,无法进行连接复用。Agent 仍然会向该服务器发起请求,但每个请求都将在新的连接上进行。
【Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The Agent will still make
the requests to that server, but each one will occur over a new connection.】
当连接被客户端或服务器关闭时,它将从连接池中移除。连接池中任何未使用的套接字都会被取消引用,以便在没有未完成请求时不会保持 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
});