首页 > 解决方案 > ExpressJS - 节点应用程序关闭后端口未释放

问题描述

当我在玩 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}`);

数据库.js

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

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

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

关键问题:

  1. 即使应用程序关闭,端口也不会被释放。

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

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

标签: mysqlnode.jsexpress

解决方案


尝试这个

// assign result of listen()
const server = app.listen(port);

// then in your SIGINT handler do this
server.close()

推荐阅读