在Express 3中关闭数据库连接

时间:2012-11-16 19:41:57

标签: node.js express

在Express 3中,当进程存在时,如何处理关闭数据库连接?

除非您明确使用HTTP服务器的.on('close', ...调用,否则不会发出.close()事件。

到目前为止,这是我最接近的,但它使用process.on代替server.on

process.on('SIGTERM', function () {
   // Close connections.
   process.exit(0);
});

1 个答案:

答案 0 :(得分:10)

基于以下信息:

-

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连接,否则节点进程将挂起。默认空闲超时为2分钟。更多信息。在node.js keep-alive超时(包括更改超时):How to set the HTTP Keep-Alive timeout in a nodejs server