2013-01-06 38 views
4

因爲我們知道節點有一些mysql模塊,有些是純js實現的(如node-mysql),有些基於c libmysql。節點mysql超時

我比較喜歡node-mysql,因爲它不需要額外的mysql庫,看起來更「乾淨」。但我也注意到它不支持在連接&查詢中的超時功能,這可能會在某種環境下導致問題。

所以我的問題是:沒有人有乾淨地解決這個超時問題?

+0

可能重複(http://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed - 連接) – Gajus

回答

1

我們做了什麼來解決這個問題是要檢查錯誤消息,並重新連接,如果有必要

這是他們表明,它在https://github.com/felixge/node-mysql#server-disconnects

下面是萬一文件發生了改變,示例代碼

function handleDisconnect(connection) { 
    connection.on('error', function(err) { 
    if (!err.fatal) { 
     return; 
    } 

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') { 
     throw err; 
    } 

    console.log('Re-connecting lost connection: ' + err.stack); 

    connection = mysql.createConnection(connection.config); 
    handleDisconnect(connection); 
    connection.connect(); 
    }); 
} 

handleDisconnect(connection); 
+0

我的意思是像連接超時事件,就像connection.on('超時',xxxx);我注意到在https://github.com/felixge/node-mysql的末尾,待辦事項列表包含「連接/查詢」的setTimeout()「 – tztxf

+0

我同意上述解決方案不解決超時。我在生產中使用上面的解決方案,它在超時失敗: - ( –

+0

這不會阻止超時發生,但會重新創建連接。我看看我們的代碼,我們正在使用這個,我們是實際上在'關閉'事件發射重新連接。 –

0

我有同樣的問題,使用方法mysql.createPool而不是方法createConnection有我的工作。

這是我的代碼;

/*jslint node: true */ 
'use strict'; 
var Q = require('q'); 

var mysql = require('mysql'); 
var _config; 
var env = process.env.NODE_ENV || 'development'; 
if (env === 'development') { 
    _config = { 
    host  : 'localhost', 
    user  : 'root', 
    charset : 'latin1', 
    password : '123456', 
    database : 'DEVDB', 
    connectionLimit: 10 
    }; 
}else { 
    _config = { 
    host : 'PRODUCTIONHOST', 
    user  : 'root', 
    charset : 'latin1', 
     password : 'PRODUCTIONPASS', 
    database: 'PRODUCTIONDB', 
    connectionLimit: 10 
    }; 
} 

var _pool = mysql.createPool(_config); 

var runquery = function() { 
    var deferred = Q.defer(); 
    var args = Array.prototype.slice.call(arguments); 

    //console.log(args); 
    args.push(function(err, results){ 
    if (err) { 
     deferred.reject(new Error(err)); 
    } else { 
     deferred.resolve(results); 
    } 
    }); 

    _pool.query.apply(_pool, args); 

    return deferred.promise; 
}; 


module.exports = runquery; 

用法示例;

runquery('select id from users where mail = ?', 'eugenioclrc') 
.then(function(rows){ 
    console.log(rows); 
}); 
的[MySQL的的NodeJS錯誤:連接丟失服務器關閉了連接]
+0

你能否詳細說明這個答案?我也使用了mysql.createPool,但它不適用於我。 – jagc