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

问题描述:

expressjs有很多优雅停止的例子,我怎样才能达到相同的koajs?如何优雅地停止koajs服务器?

我想断开数据库连接以及

我有一个猫鼬数据库连接,和2 Oracle数据库连接(https://github.com/oracle/node-oracledb

+0

我建议使用'生产pm2',支持优美的重装等。 – zeronone

我创建了一个NPM包http-graceful-shutdownhttps://github.com/sebhildebrandt/http-graceful-shutdown)前一段时间。这适用于httpexpresskoa。当你想添加自己的清理东西时,我修改了包,这样你现在就可以添加自己的清理函数,这将在关闭时调用。所以基本上这个包处理所有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.....') 
     } 
    } 
);