在使用
pg-promise
构建主/副本 postgres 连接的场景中,是否有办法在副本中断时重建这些连接? 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
模块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);
}
}
}
};