worker.disconnect()
- 返回值: <cluster.Worker> 对
worker的引用。
在工作进程中,此函数将关闭所有服务器,等待这些服务器的 '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.】
上述情况仅适用于服务器连接,客户端连接不会被工作线程自动关闭,断开连接时也不会等待它们关闭后再退出。
【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
}
});
}