简体   繁体   中英

Mongo: How to automatically connect to secondary in case of primary failure

I have a replica of three mongod instances, one of them is the primary instance, and the other two are secondary. I connected a mongo instance to the primary, and then I turned off the mongod primary instance, simulating a failure.

Typically, as soon as I initiated a command, mongo generated a DBClientCursor::init call() failed error.

My question is, in case of such a failure, where the primary cannot go back to service, and there will definitely be an election for the new primary, is there a way to tell mongo to automatically search and connect to the new primary of the replica set?

Possibly your problem is that you're only connecting to one node, the one which is primary at that time. What you need to to do is to specify, when connecting, what the replicaset is and what the address is of each available node - so your client can reconnect to a different node if its primary falls over.

The documentation on the Mongo URI connection string format explains this:

hostX : Optional. You can specify as many hosts as necessary. You would specify multiple hosts, for example, for connections to replica sets.

It gives this example:

EXAMPLE
To describe a connection to a replica set named test, with the following mongod hosts:

db1.example.net on port 27017 and
db2.example.net on port 2500.
You would use a connection string that resembles the following:

mongodb://db1.example.net,db2.example.net:2500/?replicaSet=test

You may need to check your driver's documentation also, in case it requires a particular way of specifying the replica set and the list of nodes.

This was not the problem. The replica set was well defined and configured. The problem was really weird, I'm guessing it is a bug in the terminal. All I did was I closed the terminal, opened a new one, and it was working like a charm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM