【问题标题】:ExpressJS - Port is not released after node application shuts downExpressJS - 节点应用程序关闭后端口未释放
【发布时间】:2018-08-19 01:50:00
【问题描述】:

当我在玩 ExpressJS 时,我注意到了一些相当奇怪的东西。

如果应用程序正在关闭,我正在尝试关闭所有数据库连接。 但是我注意到,即使在应用程序关闭后,8080 端口也没有释放。我将不得不手动找到持有该端口的进程的 ID 并将其终止。

很明显,我要么没有放弃数据库连接,要么存在某种连接泄漏。但我不确定究竟是什么导致了问题。

我的代码 - index.js

const express = require('express'),
    app = express(),
    db = require('./db'),
    port = process.env.PORT || 8080;

// Commenting out this portion of the code makes the problem go away.
// But I would Like to keep it so I can close all open database connections 
// before the application is closed

process.on('SIGINT',function(){
     console.log('Closing database pool');
     db.pool.end();
});

routes(app);
app.listen(port);
console.log(`API Server started on localhost:${port}`);

db.js

const config = require('./config'),
mysql = require('mysql');

exports.pool = mysql.createPool(config.mysql);

使用的数据库是托管在 AWS RDS 上的 MySQL

关键问题:

  1. 应用程序关闭后端口也不释放。

  2. 是否存在连接泄漏等问题?我应该做更多的事情来更有效地处理我的数据库连接吗?

  3. 是否有更好的方法来处理应用程序崩溃或以其他方式关闭的情况并处理所有打开的连接并安全地失败?

【问题讨论】:

    标签: mysql node.js express


    【解决方案1】:

    试试这个

    // assign result of listen()
    const server = app.listen(port);
    
    // then in your SIGINT handler do this
    server.close()
    

    【讨论】:

    • 这对我有用。谢谢!但我也想知道为什么这会奏效以及我做错了什么。您能否指出我可以阅读更多相关资源的资源?
    • 如果您要覆盖 SIGINT 的处理程序,我想您需要注意关闭您的连接。 server.close()其实有回调,但是不知道怎么在handler中等待。您也可以尝试用server.close 代替process.exit(0)db.pool.end() 的顺序也很重要,不知道那里到底发生了什么。 nodejs.org/api/http.html#http_server_close_callback
    猜你喜欢
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2014-08-29
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    相关资源
    最近更新 更多