这是我最终使用的,效果很好。偶尔连接丢失/重新启动,恢复得很好。我有一个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;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)