【发布时间】: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
关键问题:
应用程序关闭后端口也不释放。
是否存在连接泄漏等问题?我应该做更多的事情来更有效地处理我的数据库连接吗?
是否有更好的方法来处理应用程序崩溃或以其他方式关闭的情况并处理所有打开的连接并安全地失败?
【问题讨论】: