NodeJS Server with mysql hangs

落爺英雄遲暮 提交于 2019-12-07 02:35:43

问题


I am writing an application using NodeJS, Express, mysql, so far everything works fine, but when I run my application after sometime when mysql connection is interrupted my application throughs this exception and my application goes down.

Error: read ECONNRESET
    at errnoException (net.js:901:11)
    at TCP.onread (net.js:556:19)

From another stackquestion i came to know that i have to handle such uncaught exceptions like this.

process.on('uncaughtException', function(err) {
    console.log('Caught exception: ' + err);
    console.log(err.stack);
});

after this now my application does not exit, but instead it hangs up, so my question is how do I handle this exception so that mysql connection is ok even after this exception and my application does not hang up.


回答1:


I'm not sure if you're using the node-mysql module for your project, but I was, and I encountered the same ECONNRESET issue. Here's a repeat of my answer on my issue:

I reached out to the node-mysql folks on their Github page and got some firm answers.

  1. MySQL does indeed prune idle connections. There's a MySQL variable "wait_timeout" that sets the number of second before timeout and the default is 8 hours. We can set the default to be much larger than that. Use show variables like 'wait_timeout'; to view your timeout setting and set wait_timeout=28800; to change it.

  2. According to this issue, node-mysql doesn't prune pool connections after these sorts of disconnections. The module developers recommended using a heartbeat to keep the connection alive such as calling SELECT 1; on an interval. They also recommended using the node-pool module and its idleTimeoutMillis option to automatically prune idle connections.




回答2:


I found the solution and I am posting if someone else is facing the same problem this might help you guys as well.

First I caught all uncaught exceptions, which made my application not to exit abnormally.

Second the problem of hanging I had was because when server would close the connection, all my requested queries would fail and my server would simply hang up I guess its node-mysql bug, but I solved it using connecting pooling, in pooling if server close the connection its re-aquired after a second or so again so my problem was solved this way.

Here is how to make most out of node-mysql pooling



来源:https://stackoverflow.com/questions/22602362/nodejs-server-with-mysql-hangs

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