简体   繁体   中英

How to reconnect using Pool in nodejs' promise-mysql if the connection went down?

I am employing promise-mysql NodeJs library to make awaitable operations against a MySQL server.

Presently I have a simple config:

 let pool = await mysql.createPool(dbConfig);
 let connection = await pool.getConnection();

 /// after the connection is made on the program start, once,
 /// some querying using the connection follows

However, just one connection seems to get disconnected. Question: how to implement the automatic handling of a disconnect and bringing up a subsequent new connection if current one was dropped?

This is working solution for me

pool.getConnection((err, connection) => {
  if (err) {
    console.log('Error while connecting ', err)
  } else {
    if (connection) connection.release()
    console.log('Database Connected Successfully!')
  }
})

Replace this let connection = await pool.getConnection(); with above code. And execute your queries with pool and not with the connection. So, if your single connection went down or is busy, then your query will be executed with another connection from pool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM