NodeJS写了接口,客户端不停调用这个接口获取数据,大概每次访问到100的时候就会报个错(TCP.onRead),整个Node服务端都会奔溃。
找了半天发现原来是client.end()放置的位置不对,应该在返回数据之前,而我放在最后,根本不会调用到,所以连接数据库的客户端不断增大。
router.get('/getpoisummary', function(req, res) {
var ptx = req.query["x"];
var pty = req.query["y"];
var radius = req.query["r"];
if (radius > 5000){
res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'});
return res.end('{"status":"failed","message":"radius is larger than 5000 meters"}');
}
<span style="white-space:pre"> </span>var constring = "";
var client = new pg.Client(constring);
client.connect(function(err){
client.query("",function(err,result){
var rowcount = result.rowCount;
var nowdate = new Date();
console.log("query succeed : " + nowdate + ", return record num : " + rowcount);
if (rowcount == 0) {
res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'});
return res.end('{"status":"failed"}');
}
else
{
var outstr = '{"status":"ok","records":[';
for(var ii=0; ii < rowcount; ii++) {
var row = result.rows[ii];
outstr += "";
}
outstr = outstr.substr(0, outstr.length - 1);
outstr += ']}';
res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'});
return res.end(outstr);
}
client.end();
});
});
});