2017-09-15 23 views
1

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

而不是在与initOptions传递的错误函数中做process.exitCode = 1;,并重建服务启动时只有工作连接...有没有更好的方法来删除失败的连接(甚至更好,如果它的副本和process.exitCode如果它的主要)?在Nodejs中重建连接,pg-promise

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 
+0

我可以做'pgp.end()'但随后的应用程序需要知道停止接受的连接同时 – Cmag

回答

1

pg-promise模块是建立在顶部node-postgres,它使用了连接池,能够自动地恢复断开的连接的。

为此目的,你身边没有什么需要的。一旦连接再次可用,您的查询将再次开始成功。

根据您寻找的逻辑,您可以在主连接丢失时专门做process.exit(),而忽略(或仅记录)副本连接的丢失。 数据库上下文您可以在对象的构造过程中传递,它可以是任何东西 -

规定,两个通过各自的Database对象使用,你可以用dc参数的帮助区分它们。

例子:

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); 
      } 
     } 
    } 
}; 
+0

超级。谢谢你的解释:)。对于pg-promise与错误行为副本连接进行交谈的实例,其客户端请求将失败。因此,我们应该确保将另一个副本作为立即重试进行查询,或者确保对副本中断进行process.exit。 – Cmag