Advertisement
Guest User

Untitled

a guest
Jun 5th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JSON 1.41 KB | None | 0 0
  1. var db_config = {
  2.   host: 'localhost',
  3.     user: 'root',
  4.     password: '',
  5.     database: 'example'
  6. };
  7.  
  8. var connection;
  9.  
  10. function handleDisconnect() {
  11.   connection = mysql.createConnection(db_config); // Recreate the connection, since
  12.                                                   // the old one cannot be reused.
  13.  
  14.   connection.connect(function(err) {              // The server is either down
  15.     if(err) {                                     // or restarting (takes a while sometimes).
  16.       console.log('error when connecting to db:', err);
  17.       setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
  18.     }                                     // to avoid a hot loop, and to allow our node script to
  19.   });                                     // process asynchronous requests in the meantime.
  20.                                           // If you're also serving http, display a 503 error.
  21.   connection.on('error', function(err) {
  22.     console.log('db error', err);
  23.     if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
  24.       handleDisconnect();                         // lost due to either server restart, or a
  25.     } else {                                      // connnection idle timeout (the wait_timeout
  26.       throw err;                                  // server variable configures this)
  27.     }
  28.   });
  29. }
  30.  
  31. handleDisconnect();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement