Node.js MySQL 模块,连接关闭时自动重新连接数据库



我一直在使用这个 Node.js MySQL 模块来处理数据库。我的连接作为模块放置在单独的文件中。这是代码

let mysql = function connect(){
return require('mysql').createConnection({
hostname: 'localhost',
user: 'root',
password: 'root',
database: 'chat_db'
});
}
module.exports.connect = mysql;

我想稍微修改一下,以便在发生任何断开连接时,它会自动重新连接

您可以自己编写重新连接代码,但这可能需要一段时间才能正确,我认为这并不容易。我建议使用连接池来保持与 mysql 的多个连接处于打开状态,并在需要时使用它们。这将允许您定期检查连接是否仍处于活动状态,如果不是,则销毁/重新连接。管理池比管理一个非常重要的连接要容易得多。

您正在使用的库中似乎有连接池:

除了逐个创建和管理连接外,此模块还提供使用 mysql.createPool(config( 的内置连接池

https://github.com/mysqljs/mysql#pooling-connections

我成功的另一种池化选择是泛型池。具有泛型池的设置可能如下所示:

const pool = require('generic-pool');
const mysql = require('mysql');
const connections = pool.createPool({
create: (done) => {
return mysql.createConnection({
hostname: 'localhost',
user: 'root',
password: 'root',
database: 'chat_db'
}).connect(done);
},
destroy: connection => connection.destroy(),
validate: connection => connection.threadId,
}, {
testOnBorrow: true,
acquireTimeoutMillis: 10000,
min: 1,
max: size,
});

最新更新