gpt4 book ai didi

python - 连接到 MongoDB 副本集 - pymongo

转载 作者:可可西里 更新时间:2023-11-01 10:03:05 31 4
gpt4 key购买 nike

所以我有一个包含 3 个 mongo 副本集的集群。主要(主)在 rs1,而 rs2 和 rs3 是辅助。但是,主服务器可能会更改,例如,由于某些配置问题,rs2 可能在任何给定时间都是主服务器。因此,我需要能够连接到适当的副本集。假设它们位于 rs1=10.1.1.1rs2=10.1.1.2rs3=10.1.1.3。以下是我连接到 Mongo 的方式:

mongoserver_uri = "mongodb://{0}:{1}@{2}:{3}/admin".format(
username, password, host, port)
self.log.info("------- Mongo Server URI: %s --------" % mongoserver_uri)
self.client = pymongo.MongoClient(host=mongoserver_uri, ssl=True,
ssl_cert_reqs=ssl.CERT_NONE)

但是,如果像解释的那样,副本集主要更改为 rs3,那么我将无法连接到 Mongo:

  File "/home/ubuntu/myproject/mongodb.py", line 165, in clear_collections
collection.remove()
File "/usr/local/lib/python2.7/site-packages/pymongo/collection.py", line 2258, in remove
return self._delete(sock_info, spec_or_id, multi, write_concern)
File "/usr/local/lib/python2.7/site-packages/pymongo/collection.py", line 916, in _delete
codec_options=self.codec_options)
File "/usr/local/lib/python2.7/site-packages/pymongo/pool.py", line 218, in command
self._raise_connection_failure(error)
File "/usr/local/lib/python2.7/site-packages/pymongo/pool.py", line 346, in _raise_connection_failure
raise error
pymongo.errors.NotMasterError: not master

如何将其他副本集指定给 MongoClient

最佳答案

From the docs

A connection to a replica set can be made using the MongoClient() constructor, specifying one or more members of the set, along with the replica set name.

mongoserver_uri = "mongodb://{0}:{1}@{2}:{3}/admin".format(
username, password, host, port)
self.log.info("------- Mongo Server URI: %s --------" % mongoserver_uri)
self.client = pymongo.MongoClient(host=mongoserver_uri, ssl=True,
ssl_cert_reqs=ssl.CERT_NONE,
replicaset='name_of_set')

只要您连接的服务器最初在线,MongoClient 就会找到副本集的所有成员,并在故障转移时自动尝试寻找新的主服务器。

关于python - 连接到 MongoDB 副本集 - pymongo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37669209/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com