Pymongo MongoClient connect to ReplicaSet

I applied the pymongo MongoClient class to connect to replication, which has three nodes, 1 primary, 2 secondary. The code snippet is as follows:

c = MongoClient([secondary1_hostname, secondary2_hostname], replicaSet='rs0') 

When you check the three mongod logs, I find that there is always a connection created for the primary host, but the other 2 secondary ones did not receive the connection request from the client or immediately disconnected the connection. It seems that the client first reached one secondary, received the primary address, and then dropped the connection and created a long-term connection with the primary.

However, when I use the MongoReplicaSetClient class with the following code: sinppet:

 c = MongoReplicaSetClient(secondary1_name, replicaSet='rs0') 

For each member of the replica set, 3 connections are always created from the mongod log file.

So why does MongoClient's behavior always create a relationship with the primary? I read the PyMongo manual but did not find an answer. Any suggestion is appreciated.

+4
source share
3 answers

MongoClient intended only for single connections, and when accessing MongoD it will select the latter in the list of databases. When adding a replicaSet pymongo, it checks that the replica installed for the connection matches this name. It is assumed that the specified nodes are a list of visits, and pymongo should try to find all members of the set, then it will connect to the Primary node.

Another reason MongoClient accepts multiple hosts for Mongos handling and high availability: http://api.mongodb.org/python/current/examples/high_availability.html#high-availability-and-mongos MongoClient also handles replicaset configurations when you speak with a replica via Mongos.

MongoReplicaSetClient designed specifically for replication connections, it tries to find all members of the set. It also launches a replica set monitor, which allows it to quickly respond to changes in replica set configuration.

+3
source

With current pymongo (= 3.2):

 c = pymongo.MongoClient('mongodb://user: passwd@node1 :p1,node2:p2/?replicaSet=rsname') time.sleep(2) print c.nodes frozenset([(u'node1', p1), (u'node2', p2)]) 

As explained in the pymongo high availability documentation :

Addresses passed to MongoClient () are called seeds. While at least one of the seeds is online, MongoClient detects all members of the replica set and determines who is the current primary and which are secondary or arbitrage.

+2
source

The MongoClient class connects to only one host, as the documentation ( http://api.mongodb.org/python/current/api/pymongo/mongo_client.html ) says:

Create a new connection to one instance of MongoDB on the host: port.

You need to use the MongoReplicaSetClient class that you already discovered to work with a set of replicas.

+1
source

Source: https://habr.com/ru/post/956608/


All Articles