Node JS mysql database disconnect

前端 未结 1 1362
花落未央
花落未央 2021-01-03 11:21

I am using Node JS and I am trying to connect to a mysql database. It keeps getting disconnected due to a timeout so I wrote a function to reconnect if it does timeout. Alth

相关标签:
1条回答
  • 2021-01-03 11:52

    You may use sample

    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();
    
    0 讨论(0)
提交回复
热议问题