express+mysql部署到云上,每过半天就报错了,请老师和同学帮忙看看

来源:7-16 联调-介绍html页面

oyaa

2019-04-24

最近把写好的express+mysql的blog程序部署到云上,功能都正常,但是发现每过半天左右,数据库链接就关闭了,pm2的进程还能正常运行。看www-error.log日志报错如下:

0|www      |     at router.get (/root/code/blog/blog_service/routes/blog.js:32:20)
0|www      |     at Layer.handle [as handle_request] (/root/code/blog/blog_service/node_modules/express/lib/router/layer.js:95:5)
0|www      |     at next (/root/code/blog/blog_service/node_modules/express/lib/router/route.js:137:13)
0|www      |     at Route.dispatch (/root/code/blog/blog_service/node_modules/express/lib/router/route.js:112:3) code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false }
0|www      | { Error: Cannot enqueue Query after fatal error.
0|www      |     at Protocol._validateEnqueue (/root/code/blog/blog_service/node_modules/mysql/lib/protocol/Protocol.js:200:16)
0|www      |     at Protocol._enqueue (/root/code/blog/blog_service/node_modules/mysql/lib/protocol/Protocol.js:138:13)
0|www      |     at Connection.query (/root/code/blog/blog_service/node_modules/mysql/lib/Connection.js:200:25)
0|www      |     at Promise (/root/code/blog/blog_service/db/mysql.js:51:13)
0|www      |     at exec (/root/code/blog/blog_service/db/mysql.js:50:21)
0|www      |     at getMenu (/root/code/blog/blog_service/controller/menu.js:7:12)
0|www      |     at router.get (/root/code/blog/blog_service/routes/menu.js:13:20)
0|www      |     at Layer.handle [as handle_request] (/root/code/blog/blog_service/node_modules/express/lib/router/layer.js:95:5)
0|www      |     at next (/root/code/blog/blog_service/node_modules/express/lib/router/route.js:137:13)
0|www      |     at Route.dispatch (/root/code/blog/blog_service/node_modules/express/lib/router/route.js:112:3) code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false }

经过几天的调试,依然没有解决。
在网上查原因,是不活动的连接超过 wait_timeout 时间后,mysql 会主动把它释放掉,而且默认值是 8 小时!
所以试了两个方法:
1:修改/etc/my.cnf,增加 wait_timeout=388000 interactive_timeout=388000 结果依然报错
2:在mysql.js里加上重新建立链接的方法 结果还是报错

function handleDisconnect(connection) {
    connection.on('error', function(err) {
      if (!err.fatal) {
        return;
      }
   
      if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
        throw err;
      }
   
      console.log('Re-connecting lost connection: ' + err.stack);
   
      connection = mysql.createConnection(MYSQL_CONF);
      handleDisconnect(connection);
      connection.connect();
    });
  }
   
  handleDisconnect(con);

云上mysql版本是:5.7.25

请双越老师给点思路,或者哪位同学遇到过这个问题,请指教!

写回答

1回答

双越

2019-04-24

可参考 https://blog.csdn.net/liuxiao723846/article/details/46713055 这里面的 handleError 函数改一下。

1
1
oyaa
已解决
2019-04-26
共1条回复

Node.js+Express+Koa2+Nest.js 开发服务端

从入门到实战,一站式掌握 Node.js+Express+Koa2

4080 学习 · 2014 问题

查看课程