【问题标题】:rebuilding connections in Nodejs, pg-promise在 Nodejs 中重建连接,pg-promise
【发布时间】:2018-02-24 21:19:36
【问题描述】:

在使用pg-promise 构建主/副本 postgres 连接的情况下,有没有办法在副本中断的情况下重建这些连接?

而不是在与 initOptions 一起传递的错误函数中执行process.exitCode = 1; 并仅在服务启动时重建工作连接...有没有更好的方法来删除失败的连接(如果它是副本,则更好,如果它是 process.exitCode主要)?

const initOptions = {
    // global event notification;
    error: (error, e) => {
        if (e.cn) {
            //log
        }
        process.exitCode =1;
    }
};

//singleton
const pgp = require('pg-promise')(initOptions);


// then for each database in config, we connect and start the service

【问题讨论】:

  • 我可以做pgp.end() 但是应用程序需要知道在此期间停止接受连接

标签: node.js pg-promise


【解决方案1】:

模块pg-promise建立在node-postgres之上,使用连接池,能够自动恢复断开的连接。

您无需为此做任何事情。一旦连接再次可用,您的查询将再次开始成功。

根据您寻求的逻辑,您可以专门在主连接丢失时执行process.exit(),同时忽略(或仅记录)副本连接的丢失。

如果两者是通过单独的Database对象使用的,你可以借助dc参数来区分它们——Database Context,你可以在对象的构造过程中传入,它可以是任何东西。

示例:

const dbPrimary = pgp(primaryConnection, 'primary');
const dbReplica = pgp(replicaConnection, 'replica');

然后在全局error处理程序内部:

const initOptions = {
    error: (err, e) => {
        if(e.cn) {
            // connectivity issue:
            console.log(e.dc, 'connection error:', err);
            if(e.dc === 'primary') {
                process.exit(1);
            }
        }
    }
};

【讨论】:

  • 超级。谢谢你的解释:)。对于 pg-promise 与行为不端的副本连接对话的实例,其客户端请求将失败。因此,我们应该确保查询另一个副本作为立即重试,或者实际上 process.exit 在副本中断时也是如此。
猜你喜欢
  • 2017-01-27
  • 1970-01-01
  • 2017-09-01
  • 2017-04-19
  • 2017-10-10
  • 2018-02-05
  • 2016-09-12
  • 1970-01-01
  • 2021-04-25
相关资源
最近更新 更多