Fail to Reconnect Mysql in NodeJS

1

Good morning I have the following service to manage connections to mysql

var mysqlService = require( 'mysql' );
import { config } from '../../config';

var connection;
function handleDisconnect() {
  connection = mysqlService.createConnection( config ); // Recreate the connection, since
  // the old one cannot be reused.

  connection.connect( function ( err ) {              // The server is either down
    if ( err ) {                                     // or restarting (takes a while sometimes).
      console.log( 'error when connecting to db:', err );
      setTimeout( handleDisconnect, 2000 ); // We introduce a delay before attempting to reconnect,
    } else {
      console.log( "Connected To Mysql" );
    }                                     // 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 ( 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();
export const mysql = connection;

The problem is that when the connection loses the new connection it does not allow me to run queries and it returns the error: Can not enqueue Query after fatal error.

It seems as if it continues to point to the previous connection and not to the new one. Is there an error in my way of exporting the connection to be able to reuse it?

    
asked by David Scuderi 11.04.2018 в 11:00
source

1 answer

1

I have managed to solve my problem by creating a pool of mysql:

var mysqlService = require( 'mysql' );
import {  config } from '../../config';

var pool = mysqlService.createPool( config );

export const queryExecute = ( sql, params, callback ) => {
  pool.getConnection( function ( err, connection ) {
    if ( err ) {
      console.log( err );
      callback( true );
      return;
    }
    connection.query( sql, params, function ( err, results, fields ) {
      connection.release(); // always put connection back in pool after last query
      callback( err, results, fields );
    });
  });
};
    
answered by 11.04.2018 в 11:51