2016-05-23 4 views
1

Ich benutze Node JS und ich versuche, eine Verbindung zu einer MySQL-Datenbank herzustellen. Es wird wegen einer Zeitüberschreitung immer getrennt, also habe ich eine Funktion zum Wiederverbinden geschrieben, wenn es Timeouts gibt. Obwohl ich es brauche, um eine kontinuierliche Verbindung zu sein oder Referenzen in meinem Code wird nicht funktionieren. Hier ist mein entsprechenden Code:Node JS Mysql Datenbank trennen

var mysql = require('mysql'); 
var connection = mysql.createConnection({ 
    host  : '.........', // MySQL Host 
    user  : '.........', // MySQL User 
    password : '.........', // MySQL Password 
    database : '.........' // MySQL Databse 
}); 

// MYSQL INFO 

//connection.connect(); 

function replaceClientOnDisconnect(connection) { 
    connection.on("error", function (err) { 
    if (!err.fatal) { 
     console.log('Databse Error, error not fatal'); 
     return; 
    } 

    if (err.code !== "PROTOCOL_CONNECTION_LOST") { 
     throw err; 
     console.log('PROTOCOL_CONNECTION_LOST Error: Reconnecting to database...'); 
    } 

    setTimeout(function() { 
     connection.destroy(); 
     connection = mysql.createConnection(connection.config); 
     replaceClientOnDisconnect(connection); 
     connection.connect(function (error) { 
      if (error) { 
      process.exit(1); 
      } else { 
       console.log('Reconnected to database!'); 
      } 
    }, 1000); // 1 sec 
    }); 
    }); 
} 

// And run this on every connection as soon as it is created. 
replaceClientOnDisconnect(connection); 

Antwort

0

können Sie Probe verwenden

var dbConfig = { 
     host: '----', 
     user: '----', 
     password: '----', 
     database: '----', 
     port: ---- 
    }; 

var connection; 
function handleDisconnect() { 
    connection = mysql.createConnection(dbConfig); // Recreate the connection, since the old one cannot be reused. 
    connection.connect(function onConnect(err) { // The server is either down 
     if (err) {         // or restarting (takes a while sometimes). 
      console.log('error when connecting to db:', err); 
      setTimeout(handleDisconnect, 10000); // 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 onError(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();