daily pastebin goal
3%
SHARE
TWEET

Untitled

a guest Jun 5th, 2017 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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();
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top