Skip to content

Commit 63d31d3

Browse files
committed
Add MySQL reconnect.
Signed-off-by: Gao Mingfei <g199209@gmail.com>
1 parent eac7dfb commit 63d31d3

3 files changed

Lines changed: 21 additions & 4 deletions

File tree

app.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,27 @@ const mysql = require("mysql-await");
66
const fs = require("fs");
77

88
// Init MySQL connection
9-
const connection = mysql.createConnection(JSON.parse(fs.readFileSync("mysql-config.json")));
9+
var connection;
10+
11+
function reconnect() {
12+
if (connection) {
13+
connection.destroy();
14+
}
15+
connection = mysql.createConnection(JSON.parse(fs.readFileSync("mysql-config.json")));
16+
connection.connect((err) => {
17+
if (err) {
18+
console.error(`Connect to MySQL Failed, err = ${err.code}! retry in 2s.`);
19+
setTimeout(reconnect, 2000);
20+
} else {
21+
console.log("Connect to MySQL success!");
22+
}
23+
});
24+
}
25+
reconnect();
1026

1127
connection.on("error", (err) => {
1228
console.error(`MySQL Connection error ${err.code}`);
29+
reconnect();
1330
});
1431

1532
// Defining the Express app

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "mysql-rest-proxy",
3-
"version": "1.1.0",
3+
"version": "1.1.1",
44
"description": "",
55
"main": "app.js",
66
"scripts": {

0 commit comments

Comments
 (0)