1. 程式人生 > >mysql鏈接超時錯誤

mysql鏈接超時錯誤

sdn hot exp localhost 數據請求 copyright fig quest usually

最近在學習node.js是發現在MySQL連接時出現問題,當過幾個小時沒有訪問的MySQL的時候,MySQL自動斷開連接,這個問題的原因是MySQL有一個wait_time當超過這個時間的時候連接會丟失,當你再去請求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();

版權聲明:本文為博主原創+參考文章,轉載請註明出處。 https://blog.csdn.net/wb_001/article/details/79000522

mysql鏈接超時錯誤