2013-10-14 137 views
5

我在Node.js服務器上運行一個Web應用程序,我需要它始終在線,所以我永遠在使用。但這是一段時間後我得到的:Node.js - 服務器關閉了連接?

Error: Connection lost: The server closed the connection. 
    at Protocol.end (/home/me/private/app/node_modules/mysql/lib/protocol/Protocol.js:73:13) 
    at Socket.onend (stream.js:79:10) 
    at Socket.EventEmitter.emit (events.js:117:20) 
    at _stream_readable.js:910:16 
    at process._tickCallback (node.js:415:13) 
error: Forever detected script exited with code: 8 
error: Forever restarting script for 3 time 

我有兩臺服務器已連續運行了大約10天。我在所有的服務器上都有一個「keepalive」循環,每隔5分鐘左右做一個「select 1」mysql查詢,但看起來沒有任何區別。

任何想法?

編輯1個

我的其他服務器都給人一種類似的錯誤,我認爲這是「連接超時」,所以我把這個功能:

function keepalive() { 
    db.query('select 1', [], function(err, result) { 
     if(err) return console.log(err);  
     console.log('Successful keepalive.'); 
    }); 
} 

它固定我的其他兩個服務器。但在我的主服務器上,我仍然遇到上述錯誤。

這裏是我怎樣,我開始我的主服務器:

var https = require('https'); 
https.createServer(options, onRequest).listen(8000, 'mydomain.com'); 

我不知道什麼樣的代碼是你在看到感興趣。基本上服務器是一個REST API,它需要一直保持。它大約有2-5個,也許每分鐘有10個請求。

+0

它看起來像你的應用程序腳本有一些錯誤。嘗試運行'節點app.js'而不是永遠看到錯誤。 – Sriharsha

+0

在日誌中沒有可見的錯誤,我試着用node-dev運行它。這是我看到的唯一錯誤消息。 –

+0

讓我們更多地瞭解您的應用,以便了解發生了什麼。你留下一個套接字打開MySQL?爲什麼?它是一個遠程數據庫嗎? – TheBronx

回答

13

錯誤與您的HTTPS實例無關,它與您的MySQL連接有關。

到數據庫的連接意外結束並且未被處理。要解決此問題,可以使用手動重新連接解決方​​案,也可以使用自動處理重新連接的連接池。

以下是從node-mysql的文檔中摘取的手動重新連接示例。

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

對不起,延遲迴復。我剛剛用您的答案替換了我的代碼,並啓動了服務器。我們明天應該知道它是否有效:)乾杯 –

+0

它工作?還有,@hexacyanide,爲什麼甚至需要這個想法?爲什麼MySql連接偶爾會不知所措? –

+2

我剛剛第一次遇到這個錯誤。經過數月的正常運行時間後,MySQL連接突然不可用。事實證明,我安裝了一個名爲「無人蔘與升級」的軟件包,它安排了一個自動應用的MySQL安全更新,從而導致MySQL服務器重新啓動。 –

相關問題