2013-04-13 108 views
4

我在我的應用程序中使用了node-postgres。 我想知道我想要遵循的最佳實踐以確保穩定的連接。來自node.js的postgres連接

以下是我現在使用的代碼,

exports.getAll = function (args, callback) { 
helper.client = new pg.Client('tcp://postgres:system6:[email protected]/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); 
     }); 
    }); 
}; 

正如你可以在代碼中看到我連接DB爲每個請求,一旦查詢執行斷開。我還有一個想法,我只能在全局連接數據庫一次,並使用打開的連接執行查詢。代碼看起來像

helper.client = new pg.Client('tcp://postgres:system6:[email protected]/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); 
     }); 
    }); 
}; 

這裏的連接永遠不會結束。據我所知,我無法確定哪一個最好。 請建議。

謝謝..

+0

非常有趣的問題。就我所知,連接請求範圍在大多數語言中都很受歡迎。但是,我不確定它是否與Node相同。 –

回答

2

有一個在node-postgres wiki一個例子。它連接每當一個請求被處理:

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

這是我認爲是正確的,太:您的連接應在要求範圍之內。

+2

由於'node-postgres'使用連接池(默認池大小爲10個連接),所以這是一個很好的解決方案。對於不提供池並且實際上每次都必須重新連接到數據庫服務器的模塊,似乎浪費資源並且全局連接可能(以及更快)運行。 – robertklep