在Express 3中关闭数据库连接

6
在Express 3中,当进程退出时如何处理关闭数据库连接?
除非您显式地使用HTTP服务器的.close()方法,否则不会触发.on('close', ...)事件。
到目前为止,我找到的最接近的解决方案是使用process.on而不是server.on :
process.on('SIGTERM', function () {
   // Close connections.
   process.exit(0);
});
1个回答

11

基于以下信息:

--

var express = require('express');

var app = express();
var server = app.listen(1337);
var shutting_down = false;

app.use(function (req, resp, next) {
 if(!shutting_down)
   return next();

 resp.setHeader('Connection', "close");
 resp.send(503, "Server is in the process of restarting");
 // Change the response to something your client is expecting:
 //   html, text, json, etc.
});

function cleanup () {
  shutting_down = true;
  server.close( function () {
    console.log( "Closed out remaining connections.");
    // Close db connections, other chores, etc.
    process.exit();
  });

  setTimeout( function () {
   console.error("Could not close connections in time, forcing shut down");
   process.exit(1);
  }, 30*1000);

}

process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);

Connection: close头部用于告知任何 keep-alive 连接在下次发送 HTTP 请求时关闭。更多信息请参见这里:http://www.jmarshall.com/easy/http/#http1.1s4

我不确定是否有其他关闭 keep-alive 连接的方法。除非关闭 keep-alive 连接,否则 node 进程将挂起。默认的空闲超时时间为 2 分钟。有关 node.js 的 keep-alive 超时的更多信息(包括如何更改超时时间),请参见:How to set the HTTP Keep-Alive timeout in a nodejs server


为什么在以下代码中第一次设置后又将服务器变量重新定义为空?var server = app.listen(1337); var shutting_down = false; var server = null; - Arsal
1
@Arsal 感谢您指出这个问题。我认为那是一个打字错误,已经将其删除了。 - dgo.a

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接