【问题标题】:Can't add new command when connection is in closed state连接处于关闭状态时无法添加新命令
【发布时间】:2018-05-12 21:43:41
【问题描述】:

我在 Ubuntu 上使用 Amazon EC2。

我正在使用 PM2 运行服务器,因为

pm2 start bin/www --log-date-format "YYYY-MM-DD HH:mm" --watch

它工作正常,但是当我在 1 或 2 天后尝试访问 API 时。我会得到错误:

0|www      | 2017-11-29 08:30: name error  { Error: Can't add new command when connection is in closed state
0|www      |     at Connection._addCommandClosedState (/var/www/html/perb_nodejs/node_modules/mysql2/lib/connection.js:158:13)
0|www      |     at Connection.query (/var/www/html/perb_nodejs/node_modules/mysql2/lib/connection.js:621:15)
0|www      |     at Object.loginTrainer (/var/www/html/perb_nodejs/models/trainer.js:49:29)
0|www      |     at /var/www/html/perb_nodejs/routes/v1/trainer.js:50:16
0|www      |     at Layer.handle [as handle_request] (/var/www/html/perb_nodejs/node_modules/express/lib/router/layer.js:95:5)
0|www      |     at next (/var/www/html/perb_nodejs/node_modules/express/lib/router/route.js:137:13)
0|www      |     at Route.dispatch (/var/www/html/perb_nodejs/node_modules/express/lib/router/route.js:112:3)
0|www      |     at Layer.handle [as handle_request] (/var/www/html/perb_nodejs/node_modules/express/lib/router/layer.js:95:5)
0|www      |     at /var/www/html/perb_nodejs/node_modules/express/lib/router/index.js:281:22
0|www      |     at Function.process_params (/var/www/html/perb_nodejs/node_modules/express/lib/router/index.js:335:12) fatal: true }

然后我必须重新启动 PM2 实例。

我了解由于连接关闭,我遇到了这个问题。但是为什么在我使用 PM2 时会发生这种情况。我认为 PM2 应该做同样的工作。

package.json

{
  "name": "",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.18.2",
    "cookie-parser": "~1.4.3",
    "cors": "2.8.4",
    "debug": "~2.6.9",
    "express": "~4.15.5",
    "jade": "~1.11.0",
    "morgan": "~1.9.0",
    "multer": "1.3.0",
    "mysql2": "1.5.0",
    "path": "0.12.7",
    "request": "2.83.0",
    "serve-favicon": "~2.4.5"
  }
}

编辑: 我认为这不是因为服务器而是数据库连接已关闭。

任何帮助将不胜感激。

【问题讨论】:

  • 你的mysql2包有问题,如果发现问题可以pm我吗?
  • @SamuelThompson 我不认为这是 mysql2 的问题。我能找到的是,当没有 mysql 连接可以为请求提供服务时会发生这种情况。当存在内存泄漏或者我不会为 API 请求返回任何内容时,它会保持打开一个连接。特定类型后,所有连接都用完并出现该错误。

标签: node.js amazon-ec2 pm2


【解决方案1】:

我解决了我的问题,方法是在 10 秒不活动后关闭连接,然后创建一个新连接。真正的问题是无法知道连接是否打开。

【讨论】:

  • 你如何在 10 秒后关闭连接@Samuel Thompson
  • @akash 我只是在设定的超时时间内调用 mysql.close()。
  • 每次查询后?或者你能把代码截图发给你吗
  • 抱歉,已经有一段时间了。我忘记了我做了什么并且丢失了代码。在那之后我几乎重写了所有东西,所以我再也没有这个问题了。我认为这是我制作数据库的方式的一个更潜在的问题,发生了这个错误。删除连接只是一种解决方法。祝你好运!
【解决方案2】:

您需要在连接上监听error 事件,然后在它发生后打开一个新连接。以下是整个程序的外观:

for (;;) {
  try {
    const conn = await pool.getConnection();
    conn.on('error', err => {
      console.log(`Error on connection: ${err.message}`);
      // stop doing stuff with conn
    });
    try {
      // do stuff with conn
    } catch (err) {
      console.log(`Error doing stuff: ${err.message}`);
    } finally {
      conn.destroy();
    }
  } catch (err) {
    console.log(`Unable to acquire connection: ${err.message}`);
  }
  // delay before trying to reacquire connection
}

【讨论】:

    【解决方案3】:

    我遇到了同样的问题。在研究源代码时,我意识到在某些地方我们一直在使用 pool 数据库连接。所以我更改了代码,以便我们总是在每次调用后释放连接,而不是将连接从一个函数传递到另一个函数。

    let connection = await pool.getConnection();
    try {
        // Run one query 
    } finally {
        connection.release();
    }
    

    这样,池将始终返回有效的打开连接。

    当然,这仅适用于请求。在执行事务时,您仍然需要保持连接,但仅在这些情况下才这样做。

    【讨论】:

      【解决方案4】:

      我在使用池连接和 8.0.15 服务器时遇到了同样的问题,更糟糕的是,我也有长时间运行的连接。目前,我对问题得到解决持谨慎乐观的态度。必须在您的逻辑中进行一些更改:

      1. 如果您需要长时间运行的连接,那么首先检查 MySQL 服务器参数 wait_timeout - 它以秒为单位,它会在一段时间后终止静默连接,可能您只需增加这个值
      2. 如果 wait_timeout 还不够,您可以使用 connection.ping 方法,间隔一定时间 - 它会保持连接处于活动状态
      3. 在操作后分析错误对象:如果它有 fatal = true 则连接变得无用(可能它以某种方式关闭或连接丢失) - 您必须调用 connection.destroy( ) - 它将从池中移除此中毒连接,否则池可以再次提供此连接 - 可能应该在池逻辑中实施一些更改。

      【讨论】:

        【解决方案5】:

        我最终要做的是将连接请求放入它自己的 .js 文件中 - connectionRequest.js

        module.exports = function () {
        
            let mysql = require('mysql2')
            let connCreds = require('./connectionsConfig.json');
        
            //Establish Connection to the DB
            let connection = mysql.createConnection({
                host: connCreds["host"],
                user: connCreds['username'],
                password: connCreds['password'],
                database: connCreds['database'],
                port: 3306
            });
        
            //Instantiate the connection
            connection.connect(function (err) {
                if (err) {
                    console.log(`connectionRequest Failed ${err.stack}`)
                } else {
                    console.log(`DB connectionRequest Successful ${connection.threadId}`)
                }
            });
        
            //return connection object
            return connection
        }
        

        一旦我这样做了,我就可以像这样将它导入到我对控制器文件的查询中

        let connectionRequest = require('../config/connectionRequest')
        
        controllerMethod: (req, res, next) => {
            //Establish the connection on this request
            connection = connectionRequest()
        
            //Run the query
            connection.query("SELECT * FROM table", function (err, result, fields) {
                if (err) {
                    // If an error occurred, send a generic server failure
                    console.log(`not successful! ${err}`)
                    connection.destroy();
        
                } else {
                    //If successful, inform as such
                    console.log(`Query was successful, ${result}`)
        
                    //send json file to end user if using an API
                    res.json(result)
        
                    //destroy the connection thread
                    connection.destroy();
                }
            });
        },
        

        【讨论】:

          【解决方案6】:

          根据我的经验,我注意到某些节点版本中会出现此问题。 在我的情况下,我的开发是 14.17,而产品是 16.x

          prod 日志显示该错误...一旦我更改了 prod 版本,它就被修复了。

          【讨论】:

            猜你喜欢
            • 2022-07-06
            • 2019-09-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-09-28
            • 1970-01-01
            • 2010-09-29
            相关资源
            最近更新 更多