[英]NodeJS (Express) with MySQL - How to handle connection resets?
I'm running my website with NodeJS, I'm using the Express framework.我正在使用 NodeJS 运行我的网站,我正在使用 Express 框架。 Since MySQL is the only database type at my hosting, I went with it.
由于 MySQL 是我托管的唯一数据库类型,因此我选择了它。
I created a db.js file:我创建了一个 db.js 文件:
const mysql = require('mysql');
const con = mysql.createConnection({
host: .........
user: ...........
password: ............
database: ............
});
con.connect(function(err) {
if (err) {
//throw err;
console.error(err.message);
} else {
console.log('Connected Ro MySQL!');
}
});
module.exports = con;
And I using it like:我像这样使用它:
const db = require(path.join(__dirname, 'db'));
db.query('select * from table where name = ?', request.params.id, (error, result) => {
if (error) {
response.send(error.message);
} else {
//My Render Stuffs Here
});
}
});
My website works fine however sometimes let's say once every 2 weeks there is a MySQL connection reset, I think the database not available for a minute or so for some reason, and then my website crashes, I have to manually restart NodeJS what is very annoying.我的网站运行良好,但有时假设每两周一次 MySQL 连接重置,我认为数据库由于某种原因一分钟左右不可用,然后我的网站崩溃,我必须手动重新启动 NodeJS,这很烦人.
Error in the console:控制台中的错误:
node:events:355
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:211:20)
[...]
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
How should I change my codes to prevent crashing?我应该如何更改我的代码以防止崩溃? I replaced throw err;
我替换了 throw err; with the console.error(err.message);
使用 console.error(err.message); but it only works when I start the website, not when a connection reset happens at runtime.
但它仅在我启动网站时有效,而不是在运行时发生连接重置时有效。
Found the solution: Replace createConnection
with createPool
and totally remove con.connect
since createPool doesn't need it.找到解决方案:将
createConnection
替换为createPool
并完全删除con.connect
因为 createPool 不需要它。 That's it, now it's not crashes when the db unavailable.就是这样,现在当数据库不可用时它不会崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.