var mysql = require('mysql');
var mysql_config = {
host: '127.0.0.1',
user:'root',
password:'123456',
database:'workstation'
};
function handleDisconnection() {
var connection = mysql.createConnection(mysql_config);
connection.connect(function(err) {
if(err) {
setTimeout('handleDisconnection()', 2000);
}
});
connection.on('error', function(err) {
logger.error('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
logger.error('db error执行重连:'+err.message);
handleDisconnection();
} else {
throw err;
}
});
exports.connection = connection;
}
exports.handleDisconnection = handleDisconnection;
封装pool
将每一次链接放在请求中,可以避免链接失效。
var mysql=require("mysql");
var pool = mysql.createPool({
host: '127.0.0.1',
user:'root',
password:'123456',
database:'workstation'
});
var query=function(sql,options,callback){
pool.getConnection(function(err,conn){
if(err){
callback(err,null,null);
}else{
conn.query(sql,options,function(err,results,fields){
//事件驱动回调
callback(err,results,fields);
});
//释放连接,需要注意的是连接释放需要在此处释放,而不是在查询回调里面释放
conn.release();
}
});
};
module.exports=query;
网友评论