如何做优雅的停止koajs服务器?
expressjs有很多优雅的停止的例子,我怎样才能达到koajs?
我想断开数据库连接
我有一个mongoose数据库连接,和2 oracle数据库连接( https://github.com/oracle/node-oracledb )
我前一段时间创build了一个npm包http-graceful-shutdown
( https://github.com/sebhildebrandt/http-graceful-shutdown )。 这与http
, express
和koa
完美结合。 当你想添加自己的清理东西时,我修改了包,这样你现在可以添加自己的清理function,这将在关机时调用。 所以基本上这个包处理所有httpclosures的东西,再加上调用你的清理function(如果在选项中提供):
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.....') } } );