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 支持渠道上多次回答了“如何终止 HTTP 服务器”的变体。不幸的是,我无法推荐任何现有的库,因为它们以某种方式“缺乏”。从那以后,我整理了一个包,(我相信)它正在处理正常 HTTP 服务器终止所需的所有情况。
https://github.com/gajus/http-terminatorhttp-terminator它不会对 Node.js API 进行猴子补丁import Koa from 'koa';
import {
createHttpTerminator,
} from 'http-terminator';
const app = new Koa();
const server = app.listen();
const httpTerminator = createHttpTerminator({
server,
});
await httpTerminator.terminate();
AbortController
,因此不需要外部库。一个简单的例子:
const app = new Koa();
const server = http.createServer(app.callback());
const controller = new AbortController();
server.listen({
host: 'localhost',
port: 80,
signal: controller.signal
});
// middleware... etc.
app.use(async (ctx) => {
ctx.body = 'Hello World';
});
// Later, when you want to close the server.
controller.abort();
listen
函数中返回的服务器并关闭它。
import Koa from "koa";
export const createServer = async () => {
const app = new Koa();
const server = app.listen(3000);
return {app, server};
}
if (require.main === module) {
const app = createServer()
app.server.close()
}