我有一个使用postgres amazon RDS的amazon beanstalk节点应用程序。为了将节点与postgres接口,我使用了node postgres。代码如下所示:
var pg = require('pg'),
done,client;
function DataObject(config,success,error) {
var PG_CONNECT = "postgres://"+config.username+":"+config.password+"@"+
config.server+":"+config.port+"/"+config.database;
self=this;
pg.connect(PG_CONNECT, function(_error, client, done) {
if(_error){ error();}
else
{
self.client = client;
self.done = done;
success();
}
});
}
DataObject.prototype.add_data = function(data,success,error) {
self=this;
this.client.query('INSERT INTO sample (data) VALUES ($1,$2)',
[data], function(_error, result) {
self.done();
success();
});
};为了使用它,我创建了我的数据对象,然后在每次出现新数据时调用add_data。在add_data中,我调用‘this/self.one()’将连接释放回池。现在,当我反复发出这些请求时,client.query再也不会回来了。在什么情况下,这会导致数据库接口阻塞/不响应?
发布于 2015-02-11 22:56:58
您使用池的方式不正确。
您正在请求函数DataObject中的池中的连接。此函数充当构造函数,每个data object执行一次。因此,只需要从池中请求一个连接。
当我们第一次调用add_data时,查询被执行,连接被返回到池中。因此,随后的调用不会成功,因为连接已经返回。
您可以通过记录_error来验证这一点
DataObject.prototype.add_data = function(data,success,error) {
self=this;
this.client.query('INSERT INTO sample (data) VALUES ($1,$2)',
[data], function(_error, result) {
if(_error) console.log(_error); //log the error to console
self.done();
success();
});
};有几种不同的方法可以做到这一点:
add_data.client中。这是一种棘手的方式,因为调用是异步进行的,您需要注意client不是共享的,即在client.query回调函数完成之前不会发出新的请求。https://stackoverflow.com/questions/28454420
复制相似问题