【问题标题】:Closing database connection in Express 3在 Express 3 中关闭数据库连接
【发布时间】:2012-11-05 13:49:10
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    根据以下信息:

    --

    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

    【讨论】:

    • 为什么在以下行中第一次设置服务器变量后再次使用 null 定义服务器变量var server = app.listen(1337); var shutting_down = false; var server = null;
    • @Arsal 感谢您指出这一点。我认为这是一个错字。我删除了它。
    猜你喜欢
    • 2010-09-08
    • 1970-01-01
    • 2012-07-12
    • 2011-01-14
    • 1970-01-01
    • 2011-10-19
    • 2013-10-16
    相关资源
    最近更新 更多