因为我们知道节点有一些mysql模块,有些是纯js实现的(如node-mysql),有些基于c libmysql。节点mysql超时
我比较喜欢node-mysql,因为它不需要额外的mysql库,看起来更“干净”。但我也注意到它不支持在连接&查询中的超时功能,这可能会在某种环境下导致问题。
所以我的问题是:没有人有干净地解决这个超时问题?
因为我们知道节点有一些mysql模块,有些是纯js实现的(如node-mysql),有些基于c libmysql。节点mysql超时
我比较喜欢node-mysql,因为它不需要额外的mysql库,看起来更“干净”。但我也注意到它不支持在连接&查询中的超时功能,这可能会在某种环境下导致问题。
所以我的问题是:没有人有干净地解决这个超时问题?
我们做了什么来解决这个问题是要检查错误消息,并重新连接,如果有必要
这是他们表明,它在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);
我的意思是像连接超时事件,就像connection.on('超时',xxxx);我注意到在https://github.com/felixge/node-mysql的末尾,待办事项列表包含“连接/查询”的setTimeout()“ – tztxf
我同意上述解决方案不解决超时。我在生产中使用上面的解决方案,它在超时失败: - ( –
这不会阻止超时发生,但会重新创建连接。我看看我们的代码,我们正在使用这个,我们是实际上在'关闭'事件发射重新连接。 –
我有同样的问题,使用方法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错误:连接丢失服务器关闭了连接]
你能否详细说明这个答案?我也使用了mysql.createPool,但它不适用于我。 – jagc
可能重复(http://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed - 连接) – Gajus