简体   繁体   English

如何干净地异步关闭Node.js服务

[英]How to cleanly shut down a nodejs service asynchronously

My NodeJS service needs to cleanly exit in the case where either a user hits ctrl-c , or, when running on Heroku, it is shutdown (say to be restarted). 当用户点击ctrl-c ,或者当在Heroku上运行时,我的NodeJS服务需要干净地退出(即重新启动)。 To cleanly shut it down I need to perform a bunch of async actions, such as emit a 'shutdown' event to RabbitMQ (so other servics know it's gone away), close database connection cleanly, and wait for any processes that are currently mid-job to be finished. 要彻底关闭它,我需要执行一系列async操作,例如向RabbitMQ发出“ shutdown”事件(这样其他服务人员就知道它已经消失了),干净地关闭数据库连接,然后等待当前处于中间状态的任何进程,工作要完成。

The docs say that any code I run as an exit event handler can not be async. 文档说 ,我作为退出事件处理程序运行的任何代码都不能异步。

Listener functions must only perform synchronous operations. 侦听器功能只能执行同步操作。 The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. 调用“退出”事件侦听器后,Node.js进程将立即退出,从而导致仍在事件循环中排队的任何其他工作都将被放弃。

So, given that, how do I cleanly shut down my server? 因此,鉴于此,我该如何彻底关闭服务器?

This will handle ctrl-c : 这将处理ctrl-c

process.on("SIGINT", () => {
  setTimeout(() => {
    process.exit();
  }, 3000);
});

I'm not sure of the Heroku half of the question but I hope this at least helps. 我不确定问题的一半,但我希望这至少可以有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM