Mongo replica set client read write separation and failover


Original address


Pymongo is used to connect Mongo replica set so as to separate the read and write, and switch between the primary and the standby to solve the problem of primary node failure.

Replica set instance connection string URI connection example

  1. Get connection string URI connection information of replica set instance. Please refer to connection string URI for details
    Connectionstring main content:

    mongodb://username:[email protected]:27017,,
    • Replicaset: the specified name replica set
    • Authsource: Specifies the database name associated with the user credentials.authSourceDefault the database specified in the connection string.
  2. Read write separation:
    To achieve read-write separation, you need tooptionsAdd inreadPreference=secondaryPreferred, set read request as secondary node priority. Refer to read preferences for more read options.
mongodb://username:[email protected]:3007,xxxxxxxxxxxx:3007/admin?replicaSet=mgset-xxxxxx&readPreference=secondaryPreferred

The above connection string is used to connect the mongodb replica set instance. The read request will be sent to the secondary node first to realize read-write separation. At the same time, the client will automatically detect the primary / standby relationship of the node. When the primary / standby relationship changes, the write operation will be automatically switched to the new primary node to ensure the high availability of the service.

Code implementation:

def get_mongo_conn_url_replicaset(ip_port_list, user=None, pwd=None, set_name=None,set_authSource=None):
    url = 'mongodb://'
    if user is not None:
        if pwd is None:
            pwd = user
        url += '%s:%[email protected]' % (user, pwd)
    url += ','.join(ip_port_list)
    if set_name is not None:
        url += '/?replicaSet=%s&authSource=%s&readPreference=secondaryPreferred' % (set_name,set_authSource)
    return url

ip_port_list = ['', '', '']
conn_url = get_mongo_conn_url_replicaset(ip_port_list, "username", "password", "rs_3777","admin")
cli = MongoClient(conn_url)

Recommended Today

Python basics Chinese series tutorial · translation completed

Original: Python basics Python tutorial Protocol: CC by-nc-sa 4.0 Welcome anyone to participate and improve: a person can go very fast, but a group of people can go further. Online reading Apache CN learning resources catalog introduce Seven reasons to learn Python Why Python is great Learn Python introduction Executing Python scripts variable character string […]