如何优雅地停止 koajs 服务器?

Sib*_*ini 3 oracle mongoose node.js express koa

expressjs 有很多优雅停止的例子,我如何为 koajs 实现相同的停止?

我也想断开数据库连接

我有一个 mongoose 数据库连接和 2 个 oracle db 连接(https://github.com/oracle/node-oracledb

Seb*_*ndt 6

前段时间我创建了一个 npm 包http-graceful-shutdownhttps://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.....')
        }
    }
);
Run Code Online (Sandbox Code Playgroud)