MySQL Link timeout error

Source: Internet
Author: User

Recently learning node. JS was found to be a problem in MySQL connection, when MySQL was not accessed for a few hours, MySQL automatically disconnected, the problem is that MySQL has a wait_time when more than this time the connection will be lost, When you ask for MySQL again, you will not be connected to the MySQL service. The first thing to do is to sort out the two problems:

First, look at the thrown exception:

Second, the first solution: when the MySQL connection is lost will throw an exception, the exception code is ' Protocol_connection_ LOST ' When this exception is caught, the reconnection is performed, which solves the problem of connection loss: encapsulate this connection as a global module, named ' Mysqlconnection.js ' code as follows:

var mysql =Require' MySQL ');var mysql_config = {host:' 127.0.0.1 ', User:' Root ', password:' 123456 ', database:' Workstation '};functionHandledisconnection() {var connection = mysql.createconnection (mysql_config); Connection.connect (function(err) { if (err) {setTimeout (' handledisconnection () ', + )}); Connection.on (' Error ', function(err) {Logger.error (' db error ', err); if (Err.code = = = ' Protocol_connection_lost ') {logger.error (' DB error execution re-connect: ' +err.message); Handledisconnection (); } else { throw err;}}); Exports.connection = connection;} Exports.handledisconnection = handledisconnection;             

First, the connection is encapsulated into a module, and then the method of exporting the connection is ' handledisconnection ' and ' Connection '; In the place where you need to call the Handledisconnection method globally, not much to say, afraid of exposing IQ, here to pay special attention is, in the use of connection ' connection ', this ' Connection ' cannot be a global variable and should be fetched every time a data request is executed, otherwise it cannot get the latest ' connection '.

Second, using the connection pool, also encapsulates the connection into module, named ' Mysqlpool.js ' code as follows:

var mysql=Require"MySQL");var pool = Mysql.createpool ({host:' 127.0.0.1 ', User: ' 123456 ', database:  workstation '}); var query=function (sql,options,callback) {pool.getconnection ( function (err,conn) {if (err) { Callback (Err,null,null);} else{conn.query (Sql,options, Function (err,results,fields) {//event-driven callback callback (Err,results , fields); }); //release the connection, it is important to note that the connection release needs to be released here, rather than releasing Conn.release () in the query callback;} });}; Module.exports=query               

The same thing to note here is the release of the connection Problem ' conn.release (); ' Now the online can check the solution of the problem of the release connection this line of code is misplaced, I have been unable to solve the problem, they are the release of the connection this issue in the code above the first comment in //事件驱动回调 
callback(err,results,fields);
front of this, the wording is wrong, The mistake of this notation is that after you keep asking for 10 cretin, you find that the connection is not up. Therefore, the release connection should be placed in the ' conn.query ' after the execution of the query after the release of the connection is correct!!! , so it's not going to go wrong in the code above!

Attach another resolution code:

var db_config = {host: ' localhost ', User: ' Root ', password: ', database: ' Example '};var connection;function ha                                                  Ndledisconnect () {connection = Mysql.createconnection (db_config);//Recreate the connection, since  The old one cannot is reused.                                     Connection.connect (function (ERR) {///the server is either down if (err) {      Or restarting (takes a while sometimes).      Console.log (' Error when connecting to DB: ', err); SetTimeout (Handledisconnect, 2000); We introduce a delay before attempting to reconnect,}/-to-avoid a hot loop, a                                     nd to allow we node script to});                                          Process asynchronous requests in the meantime.  If you ' re also serving HTTP, display a 503 error.    Connection.on (' Error ', function (err) {Console.log (' db error ', err); if (Err.code == = ' Protocol_connection_lost ') {//CONNECTION to the MySQL server is usually handledisconnect (); Lost due to either server restart, or a} else {//connnection idle time                                  Out (the wait_timeout throw err; Server variable configures this)}});} Handledisconnect ();

Copyright NOTICE: This article for Bo Master original + reference article, reproduced please indicate the source. 79000522

MySQL Link timeout error

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.