所以我有一个包含 3 个 mongo 副本集的集群。主要(主)在 rs1,而 rs2 和 rs3 是辅助。
但是,主服务器可能会更改,例如,由于某些配置问题,rs2 可能在任何给定时间都是主服务器。因此,我需要能够连接到适当的副本集。
假设它们位于 rs1=10.1.1.1
、rs2=10.1.1.2
和 rs3=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
?
最佳答案
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/