重现MySQL错误:服务器关闭了连接(node.js)

重现MySQL错误:服务器关闭了连接(node.js),第1张

重现MySQL错误:服务器关闭了连接(node.js)

这是我最终使用的,效果很好。偶尔连接丢失/重新启动,恢复得很好。我有一个database.js文件,它建立连接并定期检查它们。

提出要求:

var conn = require('./database');var sql = 'SELECt foo FROM bar;';conn.query(sql, [userId, plugId], function (err, rows) {   // logic}

这是我的databbase.js

var mysql = require('mysql');var Common = require('./common');var conf = Common.conf;var logger = Common.logger;var connectionState = false;var connection = mysql.createConnection({  host: conf.db.hostname,  user: conf.db.user,  password: conf.db.pass,  database: conf.db.schema,  insecureAuth: true});connection.on('close', function (err) {  logger.error('mysqldb conn close');  connectionState = false;});connection.on('error', function (err) {  logger.error('mysqldb error: ' + err);  connectionState = false;});function attemptConnection(connection) {  if(!connectionState){    connection = mysql.createConnection(connection.config);    connection.connect(function (err) {      // connected! (unless `err` is set)      if (err) {        logger.error('mysql db unable to connect: ' + err);        connectionState = false;      } else {        logger.info('mysql connect!');        connectionState = true;      }    });    connection.on('close', function (err) {      logger.error('mysqldb conn close');      connectionState = false;    });    connection.on('error', function (err) {      logger.error('mysqldb error: ' + err);      if (!err.fatal) {        //throw err;      }      if (err.pre !== 'PROTOCOL_CONNECTION_LOST') {        //throw err;      } else {        connectionState = false;      }    });  }}attemptConnection(connection);var dbConnChecker = setInterval(function(){  if(!connectionState){    logger.info('not connected, attempting reconnect');    attemptConnection(connection);  }}, conf.db.checkInterval);// Mysql query wrapper. Gives us timeout and db conn refreshal! var queryTimeout = conf.db.queryTimeout;var query = function(sql,params,callback){  if(connectionState) {    // 1. Set timeout    var timedOut = false;    var timeout = setTimeout(function () {      timedOut = true;      callback('MySQL timeout', null);    }, queryTimeout);    // 2. Make query    connection.query(sql, params, function (err, rows) {      clearTimeout(timeout);      if(!timedOut) callback(err,rows);    });  } else {    // 3. Fail if no mysql conn (obviously)    callback('MySQL not connected', null);  }}// And we present the same interface as the node-mysql library!// NOTE: The escape may be a trickier for other libraries to emulate because it looks synchronousexports.query = query;exports.escape = connection.escape;


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4906213.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存