在 Nodejs、pg-promise 中重建连接

问题描述 投票:0回答:1

在使用

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
node.js pg-promise
1个回答
2
投票

模块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);
            }
        }
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.