NodeJs http.Agent 是用于每个实例还是每个主机?

Ahm*_*ven 3 sockets node.js

我想为每个主机创建具有不同设置的连接池。

const keepAliveAgent = new http.Agent({ 
  keepAlive: true,
  maxSockets: 2,
  keepAliveMsecs: 1000 * 60 * 60
});
Run Code Online (Sandbox Code Playgroud)

当我将此代理与两个不同的主机一起使用时。假设我们有如下代码。

request({
  url: 'https://host1',
  agent: keepAliveAgent
})

request({
  url: 'https://host2',
  agent: keepAliveAgent
})
Run Code Online (Sandbox Code Playgroud)

是否有 2 个套接字专用于每个主机(总共使用 4 个套接字),或者这些主机仅使用 2 个套接字(总共使用 2 个套接字)?

文档中

maxSockets 每个主机允许的最大套接字数。每个请求都将使用一个新的套接字,直到达到最大值。默认值:无穷大。

当我读到这篇文章时,我可以理解 2 + 2 个套接字将专用于每个主机,从而总共打开 4 个套接字。

实现没有任何与此相关的代码。有人可以澄清这一点吗?

eol*_*eol 6

正如您所期望的,最多将使用四个套接字,即在您的情况下,每个主机最多使用两个套接字。处理此问题的负责代码可以在这里找到: https: //github.com/nodejs/node/blob/master/lib/_http_agent.js#L155

套接字(除其他外)由主机 url 标识,并且将被重用或创建:

  var name = this.getName(options);
  if (!this.sockets[name]) {
    this.sockets[name] = [];
  }

  var freeLen = this.freeSockets[name] ? this.freeSockets[name].length : 0;
  var sockLen = freeLen + this.sockets[name].length;

  if (freeLen) {
    // we have a free socket, so use that.
    var socket = this.freeSockets[name].shift();
    // Guard against an uninitialized or user supplied Socket.
    if (socket._handle && typeof socket._handle.asyncReset === 'function') {
      // Assign the handle a new asyncId and run any init() hooks.
      socket._handle.asyncReset();
      socket[async_id_symbol] = socket._handle.getAsyncId();
    }

    // don't leak
    if (!this.freeSockets[name].length)
      delete this.freeSockets[name];

    this.reuseSocket(socket, req);
    setRequestSocket(this, req, socket);
    this.sockets[name].push(socket);
  } else if (sockLen < this.maxSockets) {
    debug('call onSocket', sockLen, freeLen);
    // If we are under maxSockets create a new one.
    this.createSocket(req, options, handleSocketCreation(this, req, true));
  } else {
    debug('wait for socket');
    // We are over limit so we'll add it to the queue.
    if (!this.requests[name]) {
      this.requests[name] = [];
    }
    this.requests[name].push(req);
  }
Run Code Online (Sandbox Code Playgroud)

假设您已经向其中发送了两个请求host1并且套接字尚未释放,则该请求将排队并在其中一个套接字可用时立即重新分配给其中一个套接字。此代码负责处理:https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L66