进程被杀死后,如何正常关闭Express Server?

在生产环境中运行Express应用程序时,我想在服务器进程被杀死(即,发送SIGTERM或SIGINT)时正常关闭服务器。

这是我的代码的简化版本:

const express = require('express');

const app = express();

app.get('/', (req, res) => res.json({ ping: true }));

const server = app.listen(3000, () => console.log('Running…'));

setInterval(() => server.getConnections(

(err, connections) => console.log(`${connections} connections currently open`)

), 1000);

process.on('SIGTERM', shutDown);

process.on('SIGINT', shutDown);

function shutDown() {

console.log('Received kill signal, shutting down gracefully');

server.close(() => {

console.log('Closed out remaining connections');

process.exit(0);

});

setTimeout(() => {

console.error('Could not close connections in time, forcefully shutting down');

process.exit(1);

}, 10000);

}

当我运行它并在浏览器中调用URL http:// localhost:3000

/时,setInterval函数中的log语句将一直打印“当前打开1个连接”,直到我真正关闭浏览器窗口为止。显然,即使关闭选项卡也会使连接保持打开状态。

因此,我要通过按Ctrl + C杀死服务器,它将在超时后运行,并在10秒钟后打印“无法关闭连接”,同时继续打印“ 1个连接打开”。

仅当我在终止进程之前关闭浏览器窗口时,才会收到“已关闭剩余的连接”消息。

回答:

如果有人感兴趣,我会自己找到解决方案(很想听听评论中的反馈)。

我为服务器上打开的连接添加了一个侦听器,将对这些连接的引用存储在数组中。关闭连接后,将从阵列中将其删除。

当服务器被杀死时,每个连接都通过调用其end方法来关闭。对于某些浏览器(例如Chrome),这还不够,所以在超时后,我会调用destroy每个连接。

const express = require('express');

const app = express();

app.get('/', (req, res) => res.json({ ping: true }));

const server = app.listen(3000, () => console.log('Running…'));

setInterval(() => server.getConnections(

(err, connections) => console.log(`${connections} connections currently open`)

), 1000);

process.on('SIGTERM', shutDown);

process.on('SIGINT', shutDown);

let connections = [];

server.on('connection', connection => {

connections.push(connection);

connection.on('close', () => connections = connections.filter(curr => curr !== connection));

});

function shutDown() {

console.log('Received kill signal, shutting down gracefully');

server.close(() => {

console.log('Closed out remaining connections');

process.exit(0);

});

setTimeout(() => {

console.error('Could not close connections in time, forcefully shutting down');

process.exit(1);

}, 10000);

connections.forEach(curr => curr.end());

setTimeout(() => connections.forEach(curr => curr.destroy()), 5000);

}

以上是 进程被杀死后,如何正常关闭Express Server? 的全部内容, 来源链接: utcz.com/qa/415372.html

回到顶部