expressjs优雅停止的例子很多,koajs如何实现?
我也想断开数据库连接
我有一个 mongoose 数据库连接和 2 个 oracle 数据库连接 ( https://github.com/oracle/node-oracledb )
最佳答案
前段时间我创建了一个 npm 包 http-graceful-shutdown
( https://github.com/sebhildebrandt/http-graceful-shutdown )。这与 http
、express
和 koa
完美配合。由于您还想添加自己的清理功能,因此我修改了包,这样您现在就可以添加自己的清理功能,该功能将在关机时调用。所以基本上这个包处理所有 http 关闭事情加上调用你的清理函数(如果在选项中提供):
const koa = require('koa');
const gracefulShutdown = require('http-graceful-shutdown');
const app = new koa();
...
server = app.listen(...); // app can be an express OR koa app
...
// your personal cleanup function - this one takes one second to complete
function cleanup() {
return new Promise((resolve) => {
console.log('... in cleanup')
setTimeout(function() {
console.log('... cleanup finished');
resolve();
}, 1000)
});
}
// this enables the graceful shutdown with advanced options
gracefulShutdown(server,
{
signals: 'SIGINT SIGTERM',
timeout: 30000,
development: false,
onShutdown: cleanup,
finally: function() {
console.log('Server gracefulls shutted down.....')
}
}
);
关于node.js - 如何为 koajs 服务器做优雅的停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43468463/