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)
这里的联系永远不会结束。据我所知,我无法决定哪一个最好。请建议。
谢谢..
node-postgres wiki中有一个示例。每当处理请求时它就会连接:
var server = http.createServer(function(req, res, next) {
pg.connect(function(err, client, done) {
Run Code Online (Sandbox Code Playgroud)
我认为这也是正确的:您的连接应该在请求范围内。
| 归档时间: |
|
| 查看次数: |
5487 次 |
| 最近记录: |