node.js - 连接处于关闭状态时无法添加新命令

标签 node.js amazon-ec2 pm2

我在 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 应该做同样的工作。

包.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"
  }
}

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

任何帮助将不胜感激。

最佳答案

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

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

以这种方式,池将始终返回有效的打开连接。

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

关于node.js - 连接处于关闭状态时无法添加新命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47548434/

相关文章:

javascript - Nodejs 中带有状态的 Ajax 调用

php - AWS Cloudfront + 负载均衡器,url 从主域更改为负载均衡器子域

java - 用于云应用程序的 JMX

javascript - 使用 PM2 和 child_process.exec 无需每次都打开新的命令提示符

javascript - Mongo ISODate - 如何检查是否已过去 30 天或更长时间?

node.js - React webapp在PROD环境中不断加载本地主机资源

javascript - Node postgres $1 IS NULL 错误

amazon-ec2 - 一个 Amazon EC2 实例可以服务多少用户?

node.js - 由于大量请求,pm2 挂起并且无法重新启动进程

node.js - 集群模式下的 pm2 不显示 Node 日志