2017-09-17 161 views
2

我使用下面的代碼將我的節點連接到mysql,用於我在我的項目中使用的所有休息apis; 我已經把它作爲我所有查詢請求的常用數據庫連接文件。mysql連接丟失錯誤nodejs

var mysql = require('mysql'); 
var db_connect = (function() { 
    function db_connect() { 
     mysqlConnConfig = { 
      host: "localhost", 
      user: "username", 
      password: "password", 
      database: "db_name" 
     }; 
    } 
    db_connect.prototype.unitOfWork = function (sql) { 
    mysqlConn = mysql.createConnection(mysqlConnConfig); 
     try { 
      sql(mysqlConn); 
     } catch (ex) { 

      console.error(ex); 
     } finally { 
      mysqlConn.end(); 
     } 
    }; 
    return db_connect; 
})(); 
exports.db_connect = db_connect; 

上面的代碼工作正常,我將使用我的查詢執行'sql'如下所示在我所有的休息API如下。

var query1 = "SELECT * FROM table1"; 
sql.query(query1,function(error,response){ 
if(error){ 
    console.log(error); 
} 
else{ 
    console.log(response); 
    } 
}) 

一切都很好至今,但問題是我正在8-12小時運行後得到的SQL協議連接錯誤 我永遠的模塊

forever start app.js 

我開始我的項目與上述永遠的模塊。 8-12小時後,我得到了下面的錯誤,我所有的休息api都無法正常工作或正在關閉。

"stack": ["Error: Connection lost: The server closed the connection.", " at Protocol.end (/path/to/my/file/node_modules/mysql/lib/protocol/Protocol.js:109:13)", " at Socket.<anonymous> (/path/to/my/file/node_modules/mysql/lib/Connection.js:102:28)", " at emitNone (events.js:72:20)", " at Socket.emit (events.js:166:7)", " at endReadableNT (_stream_readable.js:913:12)", " at nextTickCallbackWith2Args (node.js:442:9)", " at process._tickDomainCallback (node.js:397:17)"], 
"level": "error", 
"message": "uncaughtException: Connection lost: The server closed the connection.", 
"timestamp": "2017-09-13T21:22:25.271Z" 

然後,我就在我的研究解決如下配置手柄斷開。 但我正在努力配置我的sql連接如下所示與我的代碼。

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(); 

任何人都可以幫我改變我的代碼與上述代碼?

回答

1
SHOW SESSION VARIABLES LIKE '%wait_timeout'; 
SHOW GLOBAL VARIABLES LIKE '%wait_timeout'; 

其中之一被設置爲28800(8小時)。增加它。

或...抓住錯誤並重新連接。

或...檢查在您的框架中如何處理「連接池」。

但是...請注意,可能會出現網絡故障。所以,簡單地增加超時將不會處理這樣的故障。

或......不要掛在連接上這麼久。它不是很好玩。 它可能導致超過max_connections

(對不起,我不明白你的應用不夠好,具體談談這些多路徑的去追求它。)

MAX_CONNECTIONS

...wait_timeoutmax_connections一起走了笨拙的方式。如果超時時間「太高」,連接數量可能會持續增長,從而威脅到「連接太多」的錯誤。在典型的設計中,最好降低超時以防止客戶過度浪費連接到連接上。

如果你的情況是這樣的:「固定希望永遠保持連接的客戶端數」,則增加超時,但max_connections(至少不是遠遠超出了固定數量的客戶端)。

不過,如果網絡打嗝,連接可能會中斷。所以,你仍然可以「失去聯繫」。 (但是,如果一切都在同一臺機器上,這是不太可能的。)

+0

是增加那些超時會給任何其他的錯誤? – Jagadeesh

+0

你認爲這將是我的問題的原因? – Jagadeesh

+0

增加了關於max_connections –

2

它似乎在你面前提到你的代碼工作正常,我建議的方法:

1 - 更改連接你的MySQL服務器空閒超時(防止斷開)

2,發送保活或每小時簡單查詢。

最後,每次斷開連接時更改您的代碼以重新連接。

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 

connection.query("SELECT * FROM Mytable",function(err, rows, fields) { 

// Get your query result here 

}); 


    });          // 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(); 
+0

1.how改變連接的空閒超時? 2.我試着每30分鐘運行一次cron,雖然我的api正在關閉,但cron作業成功運行。 3.改變你的代碼重新連接? 這就是我掙扎..幫助PLZ? – Jagadeesh

+0

「最後,每次斷開連接後,更改您的代碼以重新連接。」? 幫助這個PLZ? – Jagadeesh

1

我已經通過池連接解決了這個問題。嘗試在這樣https://www.npmjs.com/package/mysql

var mysql = require('mysql'); 
 
var pool = mysql.createPool(...); 
 
    
 
pool.getConnection(function(err, connection) { 
 
    // Use the connection 
 
    connection.query('SELECT something FROM sometable', function (error, results, fields) { 
 
    // And done with the connection. 
 
    connection.release(); 
 
    
 
    // Handle error after the release. 
 
    if (error) throw error; 
 
    
 
    // Don't use the connection here, it has been returned to the pool. 
 
    }); 
 
});