nodejs mysql错误:连接丢失服务器关闭了连接

jac*_*Lin 76 mysql dbconnection node.js

当我使用节点mysql时,在服务器关闭TCP连接的12:00到2:00之间会出现错误.这是完整的信息:

Error: Connection lost: The server closed the connection.
at Protocol.end (/opt/node-v0.10.20-linux-x64/IM/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:920:16
at process._tickCallback (node.js:415:13)
Run Code Online (Sandbox Code Playgroud)

解决方案.但是,在我尝试这种方式后,问题也出现了.现在我不知道该怎么做.有人遇到过这个问题吗?

以下是我按照解决方案编写的方式:

    var handleKFDisconnect = function() {
    kfdb.on('error', function(err) {
        if (!err.fatal) {
            return;
        }
        if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
            console.log("PROTOCOL_CONNECTION_LOST");
            throw err;
        }
        log.error("The database is error:" + err.stack);

        kfdb = mysql.createConnection(kf_config);

        console.log("kfid");

        console.log(kfdb);
        handleKFDisconnect();
    });
   };
   handleKFDisconnect();
Run Code Online (Sandbox Code Playgroud)

Clo*_*ble 139

尝试使用此代码来处理服务器断开连接:

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();
Run Code Online (Sandbox Code Playgroud)

在你的代码中,我错过了之后的部分 connection = mysql.createConnection(db_config);

  • 只是提示:我正在通过重新启动 mysql 服务来测试重新连接,以确保一切正常。 (2认同)
  • @jackieLin你可以模拟一下情况,重启mysql服务,关于ubuntu sudo服务mysql重启 (2认同)
  • 谢谢@user3073745,这个问题通过重启解决 (2认同)

Gaj*_*jus 39

我不记得这个机制的原始用例.如今,我想不出任何有效的用例.

您的客户端应该能够检测到连接丢失的时间并允许您重新创建连接.如果使用相同的连接执行部分程序逻辑很重要,那么使用事务.

TL;博士; 不要使用这种方法.


一个实用的解决方案是强制MySQL保持连接活着:

setInterval(function () {
    db.query('SELECT 1');
}, 5000);
Run Code Online (Sandbox Code Playgroud)

我更喜欢这种连接池和处理断开连接的解决方案,因为它不需要以了解连接存在的方式构建代码.每5秒进行一次查询可确保连接保持活动状态并且PROTOCOL_CONNECTION_LOST不会发生.

此外,此方法可确保您保持相同的连接,而不是重新连接.这个很重要.考虑如果您的脚本依赖LAST_INSERT_ID()并且在没有您意识到的情况下重置了mysql连接会发生什么?

但是,这只能确保不会发生连接超时(wait_timeoutinteractive_timeout).正如所料,它将在所有其他情况下失败.因此,请务必处理其他错误.

  • 您应该根据需要连接到数据库并断开连接。该解决方案适用于连续运行并始终利用数据库连接的服务。 (2认同)
  • 这可能是有史以来最糟糕的建议!一个人建议您应该使用查询锤击数据库,以便连接不会发生?如果100个人这样做会发生什么?或者为什么不是10 000,如果你的应用程序注意到,该线程应该返回到MYSQL线程池而不是占用一个线程,这样你的弱代码就不会破坏!在这种情况下你实现了重新连接的功能,如果发生了这样的事件!这是令人难以置信的,这是一个感谢上帝,FB没有你作为首席架构师! (2认同)
  • 我已经更新了答案,以反映我不推荐这种方法.感谢Patrik的领导. (2认同)

小智 11

更好的解决方案是使用池 - 它会为您处理。

const pool = mysql.createPool({
  host: 'localhost',
  user: '--',
  database: '---',
  password: '----'
});

// ... later
pool.query('select 1 + 1', (err, rows) => { /* */ });
Run Code Online (Sandbox Code Playgroud)

https://github.com/sidorares/node-mysql2/issues/836

  • 这应该是公认的答案。使用池机制将隐藏有关如何处理连接超时的所有复杂细节。另外,MySQL 节点模块附带的“node_modules/mysql/Readme.md”文件中有有关如何使用它的文档。 (3认同)
  • @AlexisWilke,太棒了,你知道吗 - 类似的想法也适用于 mysql2 ? (2认同)

小智 9

要模拟断开的连接,请尝试

connection.destroy();
Run Code Online (Sandbox Code Playgroud)

更多信息在这里:https : //github.com/felixge/node-mysql/blob/master/Readme.md#termination-connections