expressjs-port在节点应用程序关闭后不释放

rm5edbpk  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(504)

我在玩expressjs的时候注意到一件很奇怪的事情。
如果应用程序正在关闭,我将尝试关闭所有数据库连接。但我注意到,即使在应用程序关闭之后,端口8080也没有被释放。我必须手动找到持有该端口的进程的id并将其终止。
很明显,我不是没有放弃db连接,就是存在某种连接泄漏。但我不确定到底是什么导致了这个问题。
我的代码-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
关键问题:
即使应用程序关闭,端口也不会释放。
是否存在连接泄漏等?我应该做更多的事情来更有效地处理我的数据库连接吗?
有没有更好的方法来处理应用程序崩溃或以其他方式关闭的场景,并安全地处理所有打开的连接和故障?

5kgi1eie

5kgi1eie1#

试试这个

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

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

相关问题