Mongo replica set client read write separation and failover

Time:2019-11-8

Original address

Preface:

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,mongodb1.example.com:27017,mongodb2.example.com:27017/admin?replicaSet=myRepl&authSource=admin
    • 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.
Example
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 = ['m3007.test.mongodb.m.com:3777', 's3007.test1.mongodb.m.com:3777', 's3007.test2.mongodb.m.com:3777']
conn_url = get_mongo_conn_url_replicaset(ip_port_list, "username", "password", "rs_3777","admin")
cli = MongoClient(conn_url)