微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/wenti/3279089.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐