NodeJS + mysql: using connection pool leads to deadlock tables

匆匆过客 提交于 2019-12-12 03:04:19

问题


I am using NodeJS and mysql library to access MySQL database.

When I establish single connection and repeatedly use it, it works fine:

global.mysql = mysql_module.createConnection({

        host: config.mysql.host,
        user: config.mysql.user,
        password: config.mysql.password
    });

When I use connection pool instead, I get ER_LOCK_WAIT_TIMEOUT errors in transactions.

global.mysql = mysql_module.createPool({

        host: config.mysql.host,
        user: config.mysql.user,
        password: config.mysql.password,
        database : config.mysql.database,
        connectionLimit : 50
    });

Strangely enough, the errors do occur on exactly the same data at exactly the same times. I.e. I have transaction in which I insert in three tables in a row, each time using last inserted ID from previous INSERT statement. With some data this works fine, with some data, the third INSERT produces ER_LOCK_WAIT_TIMEOUT error. When I use single connection in NodeJS, this works fine, so this must be problem related to connection pool.

Any help would be appreciated.


回答1:


No a big fan of asnwering my own questions, but problem is solved by explicitly creating connection from a pool and using it for every sql statement during transaction

pool.getConnection(function(err, connection) {
  connection.query( 'START TRANSACTION', function(err, rows) {
    // do all sql statements with connection and then
    connection.query( 'COMMIT', function(err, rows) {
       connection.release();
    }       
  });
});


来源:https://stackoverflow.com/questions/40378350/nodejs-mysql-using-connection-pool-leads-to-deadlock-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!