Auto restart database connection
This commit is contained in:
parent
a95a2f6ea8
commit
a56ef5a0f1
|
@ -19,12 +19,35 @@ module.exports = {
|
||||||
|
|
||||||
const mysql = require("mysql");
|
const mysql = require("mysql");
|
||||||
|
|
||||||
let connection = mysql.createConnection({
|
let db_config = {
|
||||||
host: process.env.DB_HOST,
|
host: process.env.DB_HOST,
|
||||||
user: process.env.DB_USER,
|
user: process.env.DB_USER,
|
||||||
password: process.env.DB_PASSWORD,
|
password: process.env.DB_PASSWORD,
|
||||||
database: process.env.DB_DATABASE
|
database: process.env.DB_DATABASE
|
||||||
|
};
|
||||||
|
let connection
|
||||||
|
// https://stackoverflow.com/a/20211143
|
||||||
|
function handleDisconnect() {
|
||||||
|
connection = mysql.createConnection(db_config); // Recreate the connection
|
||||||
|
|
||||||
|
connection.connect(function(err) {
|
||||||
|
if(err) {
|
||||||
|
console.log('error when connecting to db:', err);
|
||||||
|
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
|
||||||
|
} // to avoid a hot loop, and to allow our node script to
|
||||||
|
}); // process asynchronous requests in the meantime.
|
||||||
|
// If you're also serving http, display a 503 error.
|
||||||
|
connection.on('error', function(err) {
|
||||||
|
console.log('db error', err);
|
||||||
|
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
|
||||||
|
handleDisconnect(); // lost due to either server restart, or a
|
||||||
|
} else { // connnection idle timeout (the wait_timeout
|
||||||
|
throw err; // server variable configures this)
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
handleDisconnect(); //Start the auto-restarting connection
|
||||||
|
|
||||||
function escapeString(str) {
|
function escapeString(str) {
|
||||||
// return mysql.escape(str);
|
// return mysql.escape(str);
|
||||||
|
|
Loading…
Reference in New Issue