【问题标题】:Postgresql connection timed out in node.js and pgNode.js 和 pg 中的 Postgresql 连接超时
【发布时间】:2015-06-29 17:11:40
【问题描述】:

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

我的主要入口在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)

有没有办法防止连接超时(更好)?还是按需重新连接(最好)?我试图重新设计我的应用程序,一开始不连接到数据库,而是根据GET / 请求。此解决方案仅适用于第一个请求,然后在第二个请求中崩溃。任何见解都值得赞赏。

【问题讨论】:

    标签: node.js postgresql openshift pg


    【解决方案1】:

    您是否查看过 postgres keepalive 设置值?它发送数据包以防止空闲连接超时。 http://www.postgresql.org/docs/9.1/static/runtime-config-connection.html

    我也发现了这个类似的问题: How to use tcp_keepalives settings in Postgresql?

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

    编辑:您也可以尝试像这样启动客户端:

    var client = new pg.Client(conString);
    

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

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

    【讨论】:

    • 我已经尝试过,但似乎没有任何区别。
    • 我添加了另一种你可以尝试的方法。
    【解决方案2】:

    遇到同样的问题..告诉客户端在结束事件时关闭连接

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

    为我做了诀窍......

    【讨论】:

    • 花了一些时间,但我终于学会了这样做。基本上,对于每个请求,都必须有一个新的连接,处理,然后关闭。
    • 简单地做query.on('end', client.end)也行吗?
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 1970-01-01
      • 2014-04-13
      • 2022-10-01
      • 2016-11-27
      • 2018-07-15
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多