azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.84k stars 260 forks source link

【每日一题】- 2020-02-28 - node应用如何优雅退出? #104

Closed azl397985856 closed 4 years ago

azl397985856 commented 4 years ago

线上的应用如果挂了,如果优雅推出。 即将当前用户请求处理完,并且我不接受新的请求。

比如,有如下代码:

const http = require('http');
const server = http.createServer(function (req, res) {
  setTimeout(function () {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
  }, 4000);
}).listen(9090, function (err) {
  console.log('listening http://localhost:9090/');
  console.log('pid is ' + process.pid);
});

我们用ctrl + C来关闭node进程,那么会发生意想不到的情况,如下动图:

kill-server

如何避免这样的情况?从而实现优雅退出? 如何是集群的话,一个节点挂了我应该做些什么?

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.