111

当我使用 node mysql 时,在 12:00 到 2:00 之间出现一个错误,表明 TCP 连接被服务器关闭。这是完整的信息:

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)

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

这是我编写的解决方案:

    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();
4

6 回答 6

189

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

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

在您的代码中,我缺少之后的部分connection = mysql.createConnection(db_config);

于 2013-11-26T07:39:13.177 回答
49

我不记得我最初使用这种机制的用例。如今,我想不出任何有效的用例。

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

tl;博士; 不要使用这种方法。


一个实用的解决方案是强制 MySQL 保持连接处于活动状态:

setInterval(function () {
    db.query('SELECT 1');
}, 5000);

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

此外,此方法可确保您保持相同的连接处于活动状态,而不是重新连接。这个很重要。考虑一下如果您的脚本依赖LAST_INSERT_ID()并且 mysql 连接在您不知情的情况下被重置会发生什么?

但是,这只能确保不会发生连接超时 (wait_timeout和)。interactive_timeout正如预期的那样,在所有其他情况下它都会失败。因此,请确保处理其他错误。

于 2015-01-29T13:14:43.830 回答
16

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

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

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

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

于 2020-03-13T09:52:31.220 回答
10

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

connection.destroy();

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

于 2015-08-25T19:55:45.050 回答
1

在每个查询中创建和销毁连接可能很复杂,当我决定安装 MariaDB 而不是 MySQL 时,我对服务器迁移有些头疼。出于某种原因,文件 etc/my.cnf 中的参数 wait_timeout 的默认值为 10 秒(这导致无法实现持久性)。然后,将解决方案设置为28800,即8小时。好吧,我希望对这个“güevonada”有所帮助……对不起,我的英语不好。

于 2017-09-08T03:49:28.310 回答
0

这个模块不是一个一个地创建和管理连接,而是使用 mysql.createPool(config) 提供内置的连接池。

var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host            : 'example.org',
  user            : 'bob',
  password        : 'secret',
  database        : 'my_db'
});
 
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

这是 pool.getConnection() -> connection.query() -> connection.release() 代码流的快捷方式。使用 pool.getConnection() 对于为后续查询共享连接状态很有用。这是因为对 pool.query() 的两次调用可能使用两个不同的连接并并行运行。

于 2021-07-11T04:51:15.747 回答