在Node JS中处理MySQL断开连接后发送查询

时间:2019-04-20 10:47:22

标签: mysql node.js

我已经在Node JS中编写了一个函数来处理与MySQL服务器的连接丢失时的情况:

function sqlReconnect() {
    var con = mysql.createConnection({
        host: config.mysqlHost,
        user: config.mysqlUser,
        password: config.mysqlPassword,
        database: config.database
    });

    con.connect((err) => {
        if(err) {
            console.error(date.logDate("Could not connect to MySQL database, attempting to reconnect..."));
            setTimeout(sqlReconnect, 3000);
            return;
        } else {
            console.log(date.logDate("Connection successful"));

            // the checkWhiteList function sends an SQL query every 10 second
            setInterval(() => {checkWhiteList(con)}, 10000);
        }
    });

    con.on("error", (err) => {
        if(err.code === "PROTOCOL_CONNECTION_LOST") {
            console.log(date.logDate("Connection to MySQL database was lost, reconnecting..."));
            sqlReconnect();
            return;
        } else {
            console.log(date.logDate("There was a MySQL error: " + err));
        }
    });
}

checkWhiteList函数使用此连接每10秒运行一次SQL查询,并按如下方式调用sqlReconnect函数:

// client is the discord client
client.on("ready", () => {
    console.log(date.logDate("Bot online"));

    sqlReconnect();
});

当我通过重新启动MySQL服务器来模拟断开的连接时,会抛出此错误,但我不确定原因为何:

[2019-04-20 10:05:36] Bot online
[2019-04-20 10:05:36] Connection successful
[2019-04-20 10:06:04] Connection to MySQL database was lost, reconnecting...
[2019-04-20 10:06:04] Could not connect to MySQL database, attempting to reconnect...
.../index.js:14
        if (err) throw err;
                 ^

Error: Cannot enqueue Query after fatal error.
    at Protocol._validateEnqueue (.../node_modules/mysql/lib/protocol/Protocol.js:212:16)
    at Protocol._enqueue (.../node_modules/mysql/lib/protocol/Protocol.js:138:13)
    at Connection.query (.../node_modules/mysql/lib/Connection.js:201:25)
    at checkWhiteList (.../index.js:13:9)
    at Timeout.setInterval [as _onTimeout] (.../index.js:70:24)
    at ontimeout (timers.js:466:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:267:5)

有人可以建议为什么会这样吗?

0 个答案:

没有答案