Verbindungen brechen ab – Server-Neustarts, Idle-Timeouts, kurze Netzwerkaussetzer. Die Lösung besteht darin, den Verlust zu erkennen und verzögert neu zu verbinden, statt den Prozess in eine Endlosschleife laufen zu lassen:
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) { if (err) { // The server is either down console.log('error when connecting to db:', err); setTimeout(handleDisconnect, 10000); // Delay before retrying to // avoid a hot loop and to // let node process other // 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') { handleDisconnect(); // Connection to the MySQL // server is usually // lost due to either // server restart, or a } else { // connnection idle timeout throw err; // (the wait_timeout } // server variable }); // configures this) } handleDisconnect();Für alles, was über eine Spielanwendung hinausgeht, sollten Sie das Paket mysql2 mit einem Pool verwenden – Pools erneuern Verbindungen für Sie und ersparen Ihnen den Großteil dieser Buchführung:
var pool = mysql2.createPool(dbConfig);