Postgresql连接在node.js和pg中超时

我是node,postgresql和整个web开发业务的新手。 我目前正在编写一个简单的应用程序连接到一个PostgreSQL数据库,并显示在Web视图中的表内容。 该应用程序将在OpenShift托pipe。

我的主要条目是在server.js

 var pg = require('pg'); pg.connect(connection_string, function(err, client) { // handle error // save client: app.client = client; }); 

现在,处理GET /请求:

 function handle_request(req, res){ app.client.query('...', function(err, result){ if (err) throw err; // Will handle error later, crash for now res.render( ... ); // Render the web view with the result }); } 

我的应用程序似乎工作:表正确地呈现在Web视图中,它适用于多个连接(来自不同设备的不同Web客户端)。 但是,如果没有几分钟的请求,那么随后的请求将会使应用程序崩溃,并且超时信息。 这里是堆栈信息:

 /home/hai/myapp/server.js:98 if (err) throw err; ^ Error: This socket is closed. at Socket._write (net.js:474:19) at Socket.write (net.js:466:15) at [object Object].query (/home/hai/myapp/node_modules/pg/lib/connection.js:109:15) at [object Object].submit (/home/hai/myapp/node_modules/pg/lib/query.js:99:16) at [object Object]._pulseQueryQueue (/home/hai/myapp/node_modules/pg/lib/client.js:166:24) at [object Object].query (/home/hai/myapp/node_modules/pg/lib/client.js:193:8) at /home/hai/myapp/server.js:97:17 at callbacks (/home/hai/myapp/node_modules/express/lib/router/index.js:160:37) at param (/home/hai/myapp/node_modules/express/lib/router/index.js:134:11) at pass (/home/hai/myapp/node_modules/express/lib/router/index.js:141:5) 

有没有办法保持连接超时(更好)? 或根据需求重新连接(最好)? 我试图重新devise我的应用程序,而不是在开始时连接到数据库,而是在GET /请求。 该解决scheme仅适用于第一个请求,然后在第二个请求中崩溃。 任何洞察力是赞赏。

你看过postgres keepalive设置值吗? 它发送数据包以保持空闲连接超时。 http://www.postgresql.org/docs/9.1/static/runtime-config-connection.html

我也发现了这个类似的问题: 如何在Postgresql中使用tcp_keepalives设置?

你也可以按设定的时间间隔从数据库中执行非常小的查询。 但是,这种方法肯定是更黑客。

编辑:你也可以尝试启动这样的客户端:

 var client = new pg.Client(conString); 

在进行查询之前,您可以检查客户端是否仍然连接。 我相信你可以使用:

 if(client.connection._events != null) client.connect(); 

面对同样的问题。告诉客户端事件closures连接

 query.on('end', function() { client.end(); }); 

为我做了诡计…

您还可以将30秒的默认空闲超时更改为您所需的任何值。 例如

 pg.defaults.poolIdleTimeout = 600000; // 10 mins