mysql - 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
关键问题:
即使应用程序关闭,端口也不会被释放。
是否有连接泄漏等?我应该做更多的事情来更有效地处理我的数据库连接吗?
有没有更好的方法来处理应用程序崩溃或以其他方式关闭并处理所有打开的连接并安全失败的情况?
解决方案
尝试这个
// assign result of listen()
const server = app.listen(port);
// then in your SIGINT handler do this
server.close()
推荐阅读
- c - 在 fork 循环中生成随机数
- vba - VBA 数据解析器更改文本值
- python - 为什么我需要“从 tqdm 导入 tqdm”而不仅仅是“导入 tqdm”?
- c# - 什么命名空间包含 HolograicFrameData 类型?
- error-handling - 为什么我不能使用 println!处理匹配语句中的错误但恐慌!作品?
- java - 我需要添加哪些附加条件/代码才能使“类列表插入代码”在 JUNIT 中变为绿色?
- powershell - Unity.exe 命令行构建需要 10 分钟,但编辑器需要不到一分钟
- c - 在制表符分隔的文本文件中使用 fscanf 计算空值
- python - Python Webcolors - 没有定义的颜色名称
- javascript - 使用下一个和上一个按钮自动和手动更改幻灯片