MongoDB 的连接 URI 中是否需要 replicaSet

Do we need replicaSet in connection URI of MongoDB

当连接到 mongo 集群时,我们是否需要像下面这样的连接 URI 中的 replicaSet 选项

mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test

如果不使用 replicaSet 选项但所有节点都在连接 URI 中给出,如下所示,会发生什么情况

mongodb://db1.example.net:27017,db2.example.net:2500/

对于以上2种情况,在连接URI中给与不给replicaSet有什么好处。

您还应该指定副本集。

如果您不指定 replicaSet,那么您仍然连接到 PRIMARY 节点。但是,如果 PRIMARY 变得不可用,那么您的连接就会丢失。如果您指定 replicaSet 那么客户端将自动 re-connect 到新的主要成员。

您可以尝试使用这些命令进行测试:

  • db.hello().primary returns 当前主要成员
  • db.hostInfo().system.hostname returns 您当前连接的成员

始终建议在 MongoDB 连接字符串 URI 格式中包含 replicaSet 作为最佳做法。启用此功能将有助于探索更多选项以实现更好的应用程序连接。

包含replicaSet的优势:

  1. 启用后 client/driver 将知道副本集中的所有 other members
  2. 如果 fail-over 发生 client/driver automatically connects 到下一个可用成员且停机时间为零。
  3. 使用 readConcern 我们可以 scale the reads 更好地与其他副本成员一起使用。

replicaSet=myRepl&readConcernLevel=majority

  1. 要确认所有写入操作,我们可以使用 write concern 和 URI

replicaSet=myRepl&w=majority&wtimeoutMS=5000

  1. 我们可以启用 connection timeout 以保持更好的连接。

replicaSet=test&connectTimeoutMS=200000

  1. 确保应用程序仅使用 TLS/SSL 加密连接。

replicaSet=myRepl&ssl=true

为了更好地保护应用程序支持和连接,始终在连接字符串 URI 上使用 replicaSet。