javascript - 如何防止 Node.js 12 工作线程立即终止?
问题描述
我有一个运行 Express 服务器的 Node.js 应用程序和一个定期执行某些操作的工作线程。
当服务器停止时,我需要清理与工作线程启动时打开的外部系统的连接。
我尝试在进程上为 SIGTERM 和 SIGINT 信号添加处理程序,但这不起作用,工作线程中的处理程序函数没有被调用,当父进程收到 SIGINT 或 SIGTERM 时,它立即退出并退出代码 1,虽然父进程也有一个处理程序,这些处理程序确实被调用。
这是一个重现问题的简单代码示例:
开始.js
const http = require("http");
const express = require("express");
const path = require("path");
const { Worker } = require("worker_threads");
let myWorker = null;
process.on("SIGTERM", stop);
process.on("SIGINT", stop);
const app = express();
const server = http.Server(app);
myWorker = new Worker(path.join(__dirname, "./worker.js"));
myWorker.on("exit", code => console.info(`Worker exited with code ${code}`));
server.listen(3000);
function stop() {
console.log("Main process: stop()");
process.exit(0);
}
worker.js
process.on("SIGTERM", stop);
process.on("SIGINT", stop);
setInterval(() => console.log("beep"), 1000);
function stop() {
console.log("Worker process: stop()");
process.exit(0);
}
当我启动soWorker.js时,当我用 CTRL+C 中断进程时,我会在控制台上得到这个输出:
╰─➤ node start.js
beep
beep
beep
^CMain process: stop()
Worker exited with code 1
我期望发生的是这样的:
╰─➤ node start.js
beep
beep
beep
^CMain process: stop()
Worker process: stop()
Worker exited with code 0
我希望stop
调用工作线程中的函数,以便我可以使用它来关闭与外部系统的连接,然后优雅地退出工作线程进程并返回代码 0。
相反,工作线程以代码 1 退出,这是工作线程停止时的默认值。
我的问题:
当主进程终止时,如何在我的工作线程中执行一些清理代码?
我是否采用上述方法走在正确的轨道上?
解决方案
我主要是在这里吐痰,但我认为这会让你走上正确的轨道:
添加到 start.js
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
myWorker.once('exit', stop);
function cleanup() {
myWorker.postMessage('cleanup');
}
worker.js
const { parentPort } = require('worker_threads');
parentPort.on('message', (value) => {
if (value === 'cleanup') {
cleanup();
//then process.exit(0);
}
});
推荐阅读
- sql - 如何使用带有 max() 的子查询的 where 子句提高视图的性能?
- php - 如何显示(foreach)某个类别中的所有产品?
- r - 是否有 R 函数可以帮助我合并两个数据框?
- c# - C# MVC RedirectToAction 不更新视图
- ios - NavigationView 中的多个文本字段视图未将输入绑定到 ViewModel
- logging - 配置 WildFly 以仅记录 io.undertow.server.protocol.http.HttpOpenListener
- arrays - 如何将数组写入 Google 表格中的一行(通过脚本)?
- git - 无法克隆 Git 存储库,即使我将公钥添加到 GIthub
- python - 如何在 Python 中列出 kubernetes 集群中的所有 pod?
- reactjs - React Native(Expo) SecureStore getItemAsync