|
1 | 1 | var mysql = require('mysql');
|
2 | 2 |
|
3 |
| -var connection = mysql.createConnection({ |
| 3 | +var db_config = { |
4 | 4 | host : '127.0.0.1', // Your host - either local or cloud
|
5 | 5 | user : 'root', // your username
|
6 | 6 | password : 'root', // your password
|
7 | 7 | database : 'your-db-name' // database name
|
8 |
| -}); |
9 |
| -connection.connect(function(err) { |
10 |
| - if (err) throw err; |
11 |
| -}); |
| 8 | +}; |
| 9 | + |
| 10 | +var connection; |
| 11 | + |
| 12 | +function handleDisconnect() { |
| 13 | + connection = mysql.createConnection(db_config); // Recreate the connection, since |
| 14 | + // the old one cannot be reused. |
| 15 | + |
| 16 | + connection.connect(function(err) { // The server is either down |
| 17 | + if(err) { // or restarting (takes a while sometimes). |
| 18 | + console.log('error when connecting to db:', err); |
| 19 | + setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect, |
| 20 | + } // to avoid a hot loop, and to allow our node script to |
| 21 | + }); // process asynchronous requests in the meantime. |
| 22 | + // If you're also serving http, display a 503 error. |
| 23 | + connection.on('error', function(err) { |
| 24 | + console.log('db error', err); |
| 25 | + if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually |
| 26 | + handleDisconnect(); // lost due to either server restart, or a |
| 27 | + } else { // connnection idle timeout (the wait_timeout |
| 28 | + throw err; // server variable configures this) |
| 29 | + } |
| 30 | + }); |
| 31 | +} |
| 32 | + |
| 33 | +handleDisconnect(); |
12 | 34 |
|
13 | 35 | module.exports = connection;
|
0 commit comments