mysql链接超时错误

最近在学习node.js是发现在MySQL连接时出现问题,当过几个小时没有访问的MySQL的时候,MySQL自动断开连接,这个问题的原因是MySQL有一个wait_time当超过这个时间的时候连接会丢失,当你再去请求MySQL的时候会连接不上MySQL服务。先在整理一下解决这两个问题的方法:

一、先看抛出的异常: 
MySQL连接丢失

二、第一中解决方法:当MySQL连接丢失时会抛出一个异常,这个异常的code就是‘PROTOCOL_CONNECTION_LOST’当捕捉的这个异常的时候就执行重新连接,这样就能解决连接丢失的问题:将这个连接封装成全局module,取名为‘mysqlconnection.js’代码如下:

var mysql = require('mysql');
var mysql_config = {
    host: '127.0.0.1', user:'root', password:'123456', database:'workstation' }; function handleDisconnection() { var connection = mysql.createConnection(mysql_config); connection.connect(function(err) { if(err) { setTimeout('handleDisconnection()', 2000); } }); connection.on('error', function(err) { logger.error('db error', err); if(err.code === 'PROTOCOL_CONNECTION_LOST') { logger.error('db error执行重连:'+err.message); handleDisconnection(); } else { throw err; } }); exports.connection = connection; } exports.handleDisconnection = handleDisconnection;

首先将这个连接封装成一个module,然后向外导出连接的方法‘handleDisconnection’和‘connection’;在你需要的地方全局调用handleDisconnection方法,具体不多说了,怕暴露智商,这里要特别注意的是,在使用连接‘connection’的时候,这个‘connection’不能作为全局变量,应该在每一次执行数据请求的时候去获取,不然不能获取到最新的‘connection’。

二,使用连接池,同样将连接封装成module,取名为‘mysqlpool.js’代码如下:

var mysql=require("mysql");
var pool = mysql.createPool({
    host: '127.0.0.1', user:'root', password:'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){ //事件驱动回调 callback(err,results,fields); }); //释放连接,需要注意的是连接释放需要在此处释放,而不是在查询回调里面释放 conn.release(); } }); }; module.exports=query;

这里同样要注意的是释放连接问题‘ conn.release();’现在网上能查的这个问题的解决方法的释放连接这行代码都放错位置了,害的我一直解决不了办法,他们是将释放连接这个问题放到上面代码中第一个注释//事件驱动回调 
callback(err,results,fields);
这个的前面,这个写法是错误的,这个写法会发生的错误就是在你不停的请求10来次之后,发现连接不上了。所以,释放连接应该放在‘conn.query’之后,执行查询完之后再释放连接才是正确的!!!,所以要想上面代码中的写法才不会出错!

附另一篇解决代码:

var db_config = {
  host: 'localhost',
    user: 'root',
    password: '',
    database: 'example'
};

var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be 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, and to allow our 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 timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

handleDisconnect();
扫描二维码关注公众号,回复: 2199079 查看本文章
版权声明:本文为博主原创+参考文章,转载请注明出处。 https://blog.csdn.net/wb_001/article/details/79000522

猜你喜欢

转载自www.cnblogs.com/BlingSun/p/9321628.html
今日推荐