如何连接 mongodb 和副本集 url?

how to connect mongodb with replicaset url?

我在 Azure 上使用 MongoDB 和 replication(bitnami)。
我创建了三个 mongodb 节点(1 个主节点、1 个辅助节点和 1 个仲裁节点)。 当我尝试使用 MongoDB 连接 URI (mongodb://username:password@ip01:27017,ip02:27017,ip03:27017/?readPreference=primary&replicaSet=replicaset) 进行连接时,它会给我类似 pymongo.errors.ServerSelectionTimeoutError: 10.0.0.5:27017: timed out,10.0.0.6:27017: [Errno 113] No route to host,10.0.0.4:27017: timed out,10.0.0.7:27017: timed out
的错误 我更喜欢这个 Official Documentation (Bitnami) 用于连接 url。

connectionString = "mongodb://root:Root123@*.*.*.*:27017,*.*.*.*:27017,*.*.*.*:27017/?replicaSet=replicaset"
client= MongoClient(connectionString)
db = client['mongo_collection']
data = db.xyz.find({"x": 10})
for d in data:
    print d

根据您提供的official document

Ensure that the application is able to connect to each cluster node using its public or private IP address. To ensure connectivity, you have two options:

Host the application in the same network as the MongoDB cluster so that it can address each node using its private IP address. This is the recommended configuration for production environments. Host the application in a different network and assign public IP addresses, with appropriate firewall rules, to the cluster nodes (if not already assigned by default) so that the application can address each node using its public IP address. This configuration is not recommended for production environments.

因此,如果您在同一 Azure 虚拟网络中进行测试,则可以使用私有 IP(例如 10.0.0.6)。我在我的实验室测试,我使用 python 和这个 example.

import pymongo
client = pymongo.MongoClient("mongodb://root:<passsword>@10.0.0.6:27017,10.0.0.4:27017,10.0.0.5:27017/?replicaSet=replicaset")

db = client.test
>>> db.name
u'test'
>>> db.my_collection
Collection(Database(MongoClient(host=['10.0.0.5:27017', '10.0.0.6:27017', '10.0.0.4:27017'], document_class=dict, tz_aware=False, connect=True, replicaset='replicaset'), u'test'), u'my_collection')
>>> db.my_collection.insert_one({"x": 10}).inserted_id
ObjectId('5987cc0b9e90d52dd1860ac3')

更新:

如果你想连接你的 mongodb 个节点,你应该需要 ping 私有 IP。这是一种设计行为。

如果您想 mongodb 从您的应用程序或本地,您需要创建站点到站点 VPN 连接或点到站点 VPN 连接。