【发布时间】:2019-11-17 00:52:46
【问题描述】:
我有一个 node/express/mysql2 Web 应用程序,它通过连接池对象访问 mySql 数据库,我经常遇到以下问题:我将代码保留一段时间,然后当我回来访问运行查询的页面时我会得到的
foo 中的错误:错误:连接 ETIMEDOUT
bar 中的错误:错误:读取 ECONNRESET
我猜在另一边 mysql 看到空闲连接并关闭它们,客户端应用程序不知道,从池中获取这些连接然后遇到这些问题,很好。但我的印象是这是由 mysql2 自动处理的?
这就是我组织数据库代码的大致方式
sqlConnectionPool.js
const dbParam = require('./dbParam.js');
const sqlPool = require('mysql2/promise').createPool(dbParam.connection.prod);
module.exports = sqlPool;
dummyQuery.js
const sqlPool = require('./sqlConnectionPool.js');
module.exports.updatefoo = async (ID, sqlConnection = undefined) => {
let connection;
try {
connection = sqlConnection === undefined ? await sqlPool.getConnection() : await sqlConnection;
const [updateResult] = await connection.query('update foo set barID=?', [ID]);
if (updateResult.affectedRows !== 1) {
throw (new Error(`error on ID ${ID}`));
}
return undefined;
} catch (err) {
console.error(`Error in updatefoo: ${err}`);
return err;
} finally {
if (sqlConnection === undefined) {
connection.release();
}
}
};
我是否缺少自动处理这些错误的东西,或者根本没有遇到它们?我猜mysql2库在遇到connreset或conntimeout错误时需要关闭连接并将它们返回到池中......
谢谢!
【问题讨论】: