使用 mysql 池时服务器连接超时

Server connection timed out when using mysql pooling

所以我最近经常收到这个错误。

Error: Connection lost: The server closed the connection.
at Protocol.end (/home/node_modules/mysql/lib/protocol/Protocol.js:$
at Socket.<anonymous> (/home/node_modules/mysql/lib/Connection.js:1$
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)

我一直在寻找解决方案。我读了很多 mysql 池可以解决这个问题,我已经使用了几个星期了。错误仍然弹出。有谁知道为什么会这样?

我正在使用我在 Whosebug 上的一个答案中找到的这个基本函数。它处理我所有的查询

var mysql   = require("mysql");
var config = require('./db');
var db = config.database;

var pool = mysql.createPool({
    connectionLimit : 20,
    host: db.host,
    user: db.user,
    password: db.password,
    database: db.database
});


var DB = (function () {

    function _query(query, params, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                connection.release();
                callback(null, err);
                throw err;
            }

            connection.query(query, params, function (err, rows) {
                connection.release();
                if (!err) {
                    callback(rows);
                }
                else {
                    callback(null, err);
                }

            });

            connection.on('error', function (err) {
                connection.release();
                callback(null, err);
                throw err;
            });
        });
    };

    return {
        query: _query
    };
})();

module.exports = DB;

我正在执行这样的查询:

    DB.query("SELECT * FROM lists WHERE list_id = ?", [listId], function (result, err) {
console.log(result);

}

MySQL 服务器有一个名为interactive_timeout 的变量,这意味着,如果您的连接空闲 X 秒,服务器将关闭连接。

您可以稍微增加此值,但首选方法是确认超时并在需要查询时使用池中的新连接。

https://github.com/mysqljs/mysql#error-handling

连接池不会阻止任何超时,但连接池可确保您始终有一个连接,或者如果您的应用程序负载很重,则有多个连接。如果你的流量很小,你甚至不需要多个连接,因此,你甚至不需要连接池。

池中的每个连接都会超时,因为使用 release() 不会关闭连接而是将其还给池。

所以你的断开连接是很正常的,你应该适当地处理这个错误。

自动重新创建连接,请参阅https://github.com/mysqljs/mysql#poolcluster-options

canRetry (Default: true)
If true, PoolCluster will attempt to reconnect when connection fails. 

你是如何正确处理错误的?

为所有 MySQL 错误准备一个通用错误处理程序:

// Above:
mySqlErrorHandler = function(error) {
    if (error.code == '') { // <---- Insert in '' the error code, you need to find out
        // Connection timeout, no further action (no throw)
    } else {
        // Oh, a different error, abort then
        throw error;
    }
}

// In the function:
connection.on('error', mySqlErrorHandler);

您需要找出 error.code 超时时间。这可以通过 console.log(error.code);.

来完成