【问题标题】:Node PostgreSQL timeout a query by the client节点 PostgreSQL 超时客户端查询
【发布时间】:2015-11-01 11:17:49
【问题描述】:

我正在使用 Node 包 pg 用于 postgres (here):

npm i pg

var pg = require('pg');

我正在查询一个不属于我的大型集群,在某些情况下可能会失败。失败可能是易于处理的不良响应或无休止的查询。 请注意,我不能在数据库端引入更改 [配置或其他方式]。

有没有办法设置查询时间的超时? 我希望我的客户在设定的时间后放弃,并返回超时错误。

在文档中找不到类似的内容。

谢谢你!

【问题讨论】:

标签: javascript database node.js postgresql timeout


【解决方案1】:

最佳实践是使用初始化查询,为会话设置查询超时。

    SET statement_timeout TO 15000; # x milliseconds or 0 (turns off limitation)

这需要一个以毫秒为单位的超时参数,并应用于会话。 之后,当查询花费的时间超过指定的值时,您将收到来自服务器的错误。请注意这是应用户要求

    ERROR:  Query (150) cancelled on user's request

另请注意,这实际上取消了服务器端的查询,从而减少了负载。

【讨论】:

    【解决方案2】:

    您可以在客户端设置statement_timeout

    const { Client } = require('pg')
    
    const client = new Client({
      statement_timeout: 10000
    })
    

    或在游泳池中:

    const { Pool } = require('pg')
    
    const pool = new Pool({
      statement_timeout: 10000
    })
    

    【讨论】:

    • 谢谢,已经有一段时间了,我不再使用 Node.js,但这对未来的 Google 员工来说非常有用。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2022-01-11
    • 2016-04-18
    • 2015-11-29
    • 1970-01-01
    相关资源
    最近更新 更多