如何在node.js中的模块之间共享连接池?

时间:2016-08-03 15:29:52

标签: node.js postgresql connection-pooling node-modules pg

我对如何在node.js模块中正确实现postgres连接池知之甚少。

我的问题是:当我在需要连接到pg的每个模块中创建新池时,它是否有问题?

有没有办法为整个应用程序全局创建池?

感谢。

2 个答案:

答案 0 :(得分:5)

在文件中定义池,例如pgpool.js

var pg = require('pg');
var pool;
var config = {
  user: 'foo',
  database: 'my_db',
  password: 'secret',
  port: 5432, 
  max: 10,
  idleTimeoutMillis: 30000,
};

module.exports = {
    getPool: function () {
      if (pool) return pool; // if it is already there, grab it here
      pool = new pg.Pool(config);
      return pool;
};

像这样使用:

var db = require('./a/path/to/pgpool.js');
var pool = db.getPool();

答案 1 :(得分:0)

我建议不要导出池,而是一个提供连接的函数。使用promise-mysql

var mysql = require('promise-mysql');

var connectionPool = mysql.createPool({
  host     : "127.0.0.1",
  user     : '******',
  password : '******',
  database : '******',
  port     : '3306'
});

module.exports={

  getConnection: function(){
    return new Promise(function(resolve,reject){
      connectionPool.getConnection().then(function(connection){
        resolve(connection);
      }).catch(function(error){
        reject(error);
      });
    });
  }
} 

我已经制作了simple blog post about MySQL pool sharing,您可以在其中阅读更多内容