与获取和释放相同连接的节点的mysql池连接在每次调用时增加

时间:2017-06-21 15:28:41

标签: mysql node.js azure pool

我使用mysqljs/mysql连接到MySQL的节点应用程序 最近我通过调试实现了这一点:(服务器日志)

info: Url: /loginWeb
info: Method: POST
info: Connection 1098089 acquired
info: Connection 1098089 released
POST /loginWeb 200 214.618 ms - 186
info: Url: /loginWeb
info: Method: POST
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 released
info: Connection 1098089 released
POST /loginWeb 200 76.776 ms - 186
info: Url: /loginWeb
info: Method: POST
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 released
info: Connection 1098089 released
info: Connection 1098089 released
POST /loginWeb 200 122.202 ms - 186
info: Url: /loginWeb
info: Method: POST
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 released
info: Connection 1098089 released
info: Connection 1098089 released
info: Connection 1098089 released
POST /loginWeb 200 249.179 ms - 186
info: Url: /loginWeb
info: Method: POST
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 acquired
info: Connection 1098089 released
info: Connection 1098089 released
info: Connection 1098089 released
info: Connection 1098089 released
info: Connection 1098089 released
POST /loginWeb 200 101.805 ms - 186

正如您在日志中看到的那样,每次通话时都会获得并释放相同的连接。我不明白为什么。

我的代码是:

const mysql = require('mysql')
const pool = mysql.createPool(config.mysql)

exports.query = function (query, params, callback) {
  pool.getConnection(function (err, connection) {
    if (err) {
      log.error('getConnection -> mysql connection error: ', err)
      throw err
    }

    connection.query(query, params, function (err, rows) {
      connection.release()

      if (!err) {
        callback(null, rows)
      }
    })

    connection.on('error', function (err) {
      connection.release()
      log.error('on error -> mysql connection error: ', err)
      throw err
    })
  })

  pool.on('release', function (connection) {
    log.info('Connection %d released', connection.threadId)
  })
  pool.on('acquire', function (connection) {
    log.info('Connection %d acquired', connection.threadId)
  })
}

注意:NodeJS可以稳定连接,但几分钟后连接就会丢失并且DB返回:ECONTIMEOUT

有人可以解释这种行为吗?

1 个答案:

答案 0 :(得分:0)

在日志中,所有连接的threadId都是相同的。因此,池不再创建新连接。在我的测试中,如果我将以下代码移出" 查询"函数,然后releaseacquire事件一次只发出一次。

pool.on('release', function (connection) {
   log.info('Connection %d released', connection.threadId)
})
pool.on('acquire', function (connection) {
   log.info('Connection %d acquired', connection.threadId)
})

你还提到你遇到ECONTIMEOUT错误。通常,这是网络或防火墙问题。您可以尝试进行数据包捕获,以查看某处是否存在防火墙阻塞。如果不是这种情况,您最好报告问题here以获得进一步的帮助。