標籤:create 使用 log ons user font 驅動 整理 逾時
最近在學習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();
著作權聲明:本文為博主原創+參考文章,轉載請註明出處。79000522
mysql連結逾時錯誤