nodejs关于数据库mysql中断连接问题解决

问题:
在我开发nodejs写后台接口连接数据库时碰到一个问题,在我长时间没有链接数据库出现了一个问题:Error: Connection lost: The server closed the connection.

Error: Connection lost: The server closed the connection.
at Protocol.end (E:\services\express-demo\node_modules\mysql\lib\protocol\Protocol.js:112:13)
    at Socket.<anonymous> (E:\services\express-demo\node_modules\mysql\lib\Connection.js:94:28)
    at Socket.<anonymous> (E:\services\express-demo\node_modules\mysql\lib\Connection.js:526:10)
    at Socket.emit (events.js:412:35)

很明显链接问题。
解决:
方案一
在原先基础上加一个链接失败的重连处理机制,这样每次链接失败后都会重连,上代码
原先的mysql链接代码:

var mysql = require('mysql');
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'next_blog'
});
module.exports = connection;

优化后:

var mysql = require('mysql');
var db_config = {
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'next_blog'
}
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();
module.exports = connection;

方案二:
一个务实的解决方案是强迫MySQL保持连接的活力。
每5秒进行一次查询,可以确保连接保持活力

setInterval(function () {
  connection.query('SELECT 1');
}, 5000);
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值