记 node-mysql 掉进 mysql 的 wait_timeout 参数的坑

记 node-mysql 掉进 mysql 的 wait_timeout 参数的坑_第1张图片
TMS

公司 tms(Node.js + Python 开发的上线工具)碰到神奇的问题,『使用一段时间后』,express.js 还正常跑着,却打不开需要数据库查询的页面,过 30s 后转到 nginx 的报错页。

tms-web-prd-1 (err): Error: read ETIMEDOUT
tms-web-prd-1 (err):     at exports._errnoException (util.js:949:11)
tms-web-prd-1 (err):     at TCP.onread (net.js:563:26)
tms-web-prd-1 (err):     --------------------
tms-web-prd-1 (err):     at Protocol._enqueue (/home/dev1/app-prd/tms-web/node_modules/mysql/lib/protocol/Protocol.js:141:48)
tms-web-prd-1 (err):     at PoolConnection.query (/home/dev1/app-prd/tms-web/node_modules/mysql/lib/Connection.js:201:25)
tms-web-prd-1 (err):     at /home/dev1/app-prd/tms-web/libs/db.js:22:20

第一反映是数据连接未释放,使用一段时间溢出连接池导致的。检查代码,有正确释放,改大连接数量,调整超时时间,无效。
一番折腾后发现是 mysql 默认配置的 wait_timeout 作怪:不活动的连接超过 wait_timeout 时间后,mysql 会主动把它释放掉,而且默认值是 8 小时!
我们应用中 node-mysql 在项目启动时创立 connect-pool 一次,后续的 connect 都是复用。半夜和周末常会出现大于 8 个小时不使用的情况,mysql 把连接挂掉,node-mysql 还在尝试复用之前的 connect,导致了这个问题。

以为是『使用一段时间后出现的 bug』,竟然是『 8 个小时不使用就会出错』,倒也有趣~

解决方法:

治标:调整 mysql 默认的 wait_timeout 参数

治标不治本的方案,不合理但的确有效,比如改成 30 天,一个应用 30 天总会有人访问,间接避免了空闲连接被弃用的情况。wait_timeout 改大也不利于 mysql 优化,看 DBA 会不会骂死你 ;)

不过这个方案用来改成 30s 来做测试重现这个 bug 还是不错的。

tips:
win 最大支持 2147483(24.855127315 天)
其它系统最大支持 31536000(365天)
参见这里

治本:nodejs web 端处理 mysql 重连

这个是很自然的思路,谁知翻遍 node-mysql 文档只有 connect.on('error', func),没有 pool.on('error', func)。如下 变通的实现方式,可以重新连接。使用连接池没找到方便的重置方式挺遗憾的。

function handleDisconnect() {
    // Recreate the connection, since
    // the old one cannot be reused.
    connection = mysql.createConnection(dbConfig);

    connection.connect(function(err) {
        // The server is either down
        // or restarting
        if(err) {
            // 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.
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect, 2000);
        }
    });
    connection.on('error', function(err) {
        console.log('db error', err);
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        }else{
            throw err;
        }
    });
}

总结

治本的方式当然是程序自洽,无论依赖 mysql 的 wait_timeout 时间是多少都能重新建立连接。因 node-mysql 的不完善,handle disconnect 的方式有些扰也是不得也的正解。
至于 wait_timeout,知道有这个优化 db 的参数又能测试自身程序重连逻辑就好,db 的事儿要从 db 的角度去思考。

参考

  • "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR" after connection was lost, recreated · Issue #900 · felixge/node-mysql
  • 在Node.js使用mysql模块时遇到的坑 - CNode技术社区
  • 用Nodejs连接MySQL | 粉丝日志

你可能感兴趣的:(记 node-mysql 掉进 mysql 的 wait_timeout 参数的坑)