来自 Node.js 的 postgres 连接

sta*_*.js 5 node.js node-postgres

我在我的应用程序中使用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);
        });
    });
};
Run Code Online (Sandbox Code Playgroud)

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

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);
        });
    });
};
Run Code Online (Sandbox Code Playgroud)

这里的联系永远不会结束。据我所知,我无法决定哪一个最好。请建议。

谢谢..

Seb*_*eer 3

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

var server = http.createServer(function(req, res, next) {
  pg.connect(function(err, client, done) {
Run Code Online (Sandbox Code Playgroud)

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

  • 由于“node-postgres”使用连接池(默认池大小为 10 个连接),因此这是一个很好的解决方案。对于不提供池化的模块,并且实际上每次都必须重新连接到数据库服务器,这似乎浪费资源,并且全局连接可能也同样有效(并且更快)。 (2认同)