worker.disconnect()


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

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

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

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

使 .exitedAfterDisconnect 被设置。

¥Causes .exitedAfterDisconnect to be set.

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

¥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.

以上只适用于服务端连接,客户端连接不会被 worker 自动关闭,disconnect 也不会等到他们关闭才退出。

¥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.

在一个 worker 中,process.disconnect 存在,但不是这个函数;它是 disconnect()

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

因为长期存在的服务器连接可能会阻止工作进程断开连接,所以发送消息可能很有用,因此可以采取特定于应用的操作来关闭它们。实现超时也可能很有用,如果 '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.isPrimary) {
  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('node: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
    }
  });
}