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

标签 node.js sockets

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

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

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

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

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

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

documentation

maxSockets Maximum number of sockets to allow per host. Each request will use a new socket until the maximum is reached. Default: Infinity.

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

但是implementation没有任何与此相关的代码。有人可以澄清一下吗?

最佳答案

正如您所期望的,最多将使用四个套接字,即您的情况下每个主机最多使用两个套接字。处理这个问题的负责代码可以在这里找到: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);
  }

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

关于node.js - NodeJs http.Agent 是用于每个实例还是每个主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55548192/

相关文章:

c++ - 我应该通过套接字以一次读\写还是多个 block 的方式发送文件?

java - 服务器套接字退出监听时如何恢复

c# - C#.net 4.5-异步任务和套接字

node.js - 如何保持服务器客户端连接

node.js - 如何在单个 AWS EC2 实例上的 Node 中部署多个微服务?

javascript - 使用 get 请求进行多个数据库查询

javascript - socket.io 客户端在长 Node.js 函数中自动断开连接

c++ - 我们如何从 select() 函数中获取套接字列表?

c++ - 客户端/服务器 C++ 之间的通信问题

node.js - 通过nodejs和express使用 "vaadin file upload"( polymer )时出错