worker.disconnect()


在工作进程中,此函数将关闭所有服务器,等待那些服务器上的 'close' 事件,然后断开 IPC 通道。

在主进程中,内部的消息被发送给工作进程,使其调用自身的 .disconnect()

使 .exitedAfterDisconnect 被设置。

服务器关闭后,它将不再接受新连接,但连接可能会被任何其他监听的工作进程接受。 现有的连接将被允许像往常一样关闭。 当不再存在连接时(参见 server.close()),到工作进程的 IPC 通道将关闭,允许其正常地死亡。

以上仅适用于服务器连接,客户端连接不会被工作进程自动关闭,并且断开连接不会等待它们关闭才退出。

在工作进程中,process.disconnect 是存在的,但不是这个函数;它是 disconnect()

因为长期存在的服务器连接可能会阻止工作进程断开连接,所以发送消息可能很有用,因此可以采取特定于应用程序的操作来关闭它们。 实现超时也可能很有用,如果 'disconnect' 事件在一段时间后没有触发,则杀死工作进程。

if (cluster.isMaster) {
  const worker = cluster.fork();
  let timeout;

  worker.on('listening', (address) => {
    worker.send('shutdown');
    worker.disconnect();
    timeout = setTimeout(() => {
      worker.kill();
    }, 2000);
  });

  worker.on('disconnect', () => {
    clearTimeout(timeout);
  });

} else if (cluster.isWorker) {
  const net = require('net');
  const server = net.createServer((socket) => {
    // 连接永远不会结束
  });

  server.listen(8000);

  process.on('message', (msg) => {
    if (msg === 'shutdown') {
      // 发起正常关闭与服务器的任何连接
    }
  });
}

In a worker, this function will close all servers, wait for the 'close' event on those servers, and then disconnect the IPC channel.

In the master, an internal message is sent to the worker causing it to call .disconnect() on itself.

Causes .exitedAfterDisconnect to be set.

After a server is closed, it will no longer accept new connections, but connections may be accepted by any other listening worker. Existing connections will be allowed to close as usual. When no more connections exist, see server.close(), the IPC channel to the worker will close allowing it to die gracefully.

The above applies only to server connections, client connections are not automatically closed by workers, and disconnect does not wait for them to close before exiting.

In a worker, process.disconnect exists, but it is not this function; it is disconnect().

Because long living server connections may block workers from disconnecting, it may be useful to send a message, so application specific actions may be taken to close them. It also may be useful to implement a timeout, killing a worker if the 'disconnect' event has not been emitted after some time.

if (cluster.isMaster) {
  const worker = cluster.fork();
  let timeout;

  worker.on('listening', (address) => {
    worker.send('shutdown');
    worker.disconnect();
    timeout = setTimeout(() => {
      worker.kill();
    }, 2000);
  });

  worker.on('disconnect', () => {
    clearTimeout(timeout);
  });

} else if (cluster.isWorker) {
  const net = require('net');
  const server = net.createServer((socket) => {
    // Connections never end
  });

  server.listen(8000);

  process.on('message', (msg) => {
    if (msg === 'shutdown') {
      // Initiate graceful close of any connections to server
    }
  });
}