【发布时间】:2014-06-13 12:56:52
【问题描述】:
有什么问题?
- 我正在使用 node-mysql 连接到 mysql。
- 我很难处理
server disconnects/wait_timeouts如此处所述:https://github.com/felixge/node-mysql#server-disconnects - 每次在处理
PROTOCOL_CONNECTION_LOST错误时尝试重新创建连接后,我都会收到错误消息:This socket has been ended by the other party。
我想要做什么
// Connect Function
db.connect = function(callback){
// Destory the Connection if there is already one
if(db.connection) {
console.log('[mysql]','connection destroy');
db.connection.destroy();
db.connection = null;
}
// Create the Connection
db.connection = MySQL.createConnection(options);
// Connect using the Connection
db.connection.connect(function(error) {
if(error){
console.log('[mysql]', 'connect failed', error);
} else {
console.log('[mysql]', 'connection success');
db.connection.database = options.database;
callback(db.connection, error);
}
});
// Listen on Connection Errors
db.connection.on('error', function(error) {
// Connection to the MySQL server is usually
// lost due to either server restart, or a
// connnection idle timeout (the wait_timeout server variable configures this)
if(error.code === 'PROTOCOL_CONNECTION_LOST') {
console.log('[mysql]', 'PROTOCOL_CONNECTION_LOST')
db.connect(callback);
} else {
console.log('[mysql] Connection Error: ', error);
}
});
// Return Connection Instance
return db.connection;
}
其他详情
wait_timeout 和 interactive_timeout 必须在 my.cnf 中设置大约 10 秒才能测试问题。
[mysqld]
wait_timeout = 10
interactive_timeout = 10
【问题讨论】:
标签: javascript mysql node.js error-handling connection