【问题标题】:postgres connection from node.js来自 node.js 的 postgres 连接
【发布时间】:2013-04-13 23:12:44
【问题描述】:

我在我的应用程序中使用node-postgres。 我想知道我想遵循的最佳做法以确保稳定的连接。

以下是我现在使用的代码,

exports.getAll = function (args, callback) {
helper.client = new pg.Client('tcp://postgres:system6:5432@192.168.143.11/abc_dev');
helper.client.connect();
helper.client.query('select count(1) as total_records from facilities', function(err,response){
    helper.client.query('select * ,'+response.rows[0].total_records+' as total_records  from facilities', 
        function(err,response){
            callback(response);
            helper.client.end.bind(helper.client);
        });
    });
};

正如您在代码中看到的,我为每个请求连接数据库,并在查询执行后断开连接。我还有一个想法,我只能在全局范围内连接数据库一次并使用打开的连接执行查询。代码看起来像

helper.client = new pg.Client('tcp://postgres:system6:5432@192.168.143.11/abc_dev');
helper.client.connect();

exports.getAll = function (args, callback) {
helper.client.query('select count(1) as total_records from facilities', function(err,response){
    helper.client.query('select * ,'+response.rows[0].total_records+' as total_records  from facilities', 
        function(err,response){
            callback(response);
        });
    });
};

在这里,连接永远不会结束。据我所知,我无法决定哪一个是最好的。 请提出建议。

谢谢..

【问题讨论】:

  • 非常有趣的问题。据我所知,请求范围的连接在大多数语言中都很流行。但是,我不确定它是否与 Node 相同。

标签: node.js node-postgres


【解决方案1】:

node-postgres wiki 中有一个示例。每当处理请求时它都会连接:

var server = http.createServer(function(req, res, next) {
  pg.connect(function(err, client, done) {

这也是我认为正确的:您的连接应该在请求范围内。

【讨论】:

  • 由于node-postgres 使用连接池(默认池大小为10 个连接),这是一个很好的解决方案。对于不提供池化的模块,实际上每次都必须重新连接到数据库服务器,这似乎是一种资源浪费,而全局连接可能同样有效(而且速度更快)。
猜你喜欢
  • 2011-03-22
  • 2011-09-21
  • 2014-09-07
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多