mysql.createPool(db)_nodejs解决mysql和连接池(pool)自动断开问题

最近在做一个个人项目,数据库尝试使用了mongodb、sqlite和mysql。分享一下关于mysql的连接池用法。项目部署于appfog,项目中我使用连接池链接数据库,本地测试一切正常。上线以后,经过几次请求两个数据接口总是报503。一直不明就里,今天经过一番排查终于顺利解决了。

1.mysql 链接普通模式varmysql = require('mysql'),

env = {

host : 'localhost',

user : 'root',

password : '2212',

database : 'image_marker'

};

db = mysql.createConnection(env);

db.connect();

exports.do=function(sql, callback) {

db.query(sql, callback);

}

MySQL中有一个名叫wait_timeout的变量,表示操作超时时间,当连接超过一定时间没有活动后,会自动关闭该连接,这个值默认为28800(即8小时)。对于这种普通连接的方式,在正式线上可能会遇到连接丢失的问题(No reconnection after connection lost错误日志),上github上看了下文档和issues,上面说到连接丢失后不会自动重新连接,会触发error事件。 所以可以使用下面这种方法来避免连接对视问题:

functionhandleError (err) {

if(err) {

// 如果是连接断开,自动重新连接

if(err.code ==='PROTOCOL_CONNECTION_LOST') {

connect();

} else{

console.error(err.stack || err);

}

}

}

// 连接数据库

functionconnect () {

db = mysql.createConnection(config);

db.connect(handleError);

db.on('error', handleError);

}

vardb;

connect();

2.使用连接池

对于丢失连接的问题,可以使用连接池(最新版mysql模块,用mysql.createPool()来创建的pool,当触发了connection的error事件时,会把该connection对象从连接池中移除。)varmysql = require('mysql');

varpool  = mysql.createPool(config);

pool.getConnection(function(err, connection) {

// Use the connection

connection.query( 'SELECT something FROM sometable',function(err, rows) {

// And done with the connection.

connection.end();

// Don't use the connection here, it has been returned to the pool.

});

});

你可能感兴趣的:(mysql.createPool(db)_nodejs解决mysql和连接池(pool)自动断开问题)