Mongodb Java driver cannot connect to primary after crash

I had a problem while trying to fault tolerance mongodb with java driver.

I have a primary / secondary mongodb cluster, namely server1 and server2.

When I kill primary server1 in order to simulate a failure, server2 becomes the main one in a few seconds, and my applications that access the mango using the java driver start using the new primary server2.

When I restarted server1, it takes its main role in a few seconds, but then my application, instead of connecting to server 1, is still trying to connect to server2 and, since it is now in a secondary state, it’s checked! All requests are resolved by this error:

com.mongodb.MongoServerSelectionException: Unable to connect to any server that matches {serverSelectors=[ReadPreferenceServerSelector{readPreference=primary}, LatencyMinimizingServerSelector{acceptableLatencyDifference=15 ms}]} 

I am using mongodb 2.6 and java driver 2.12. I do not pass any parameter to my MongoClient, which is created using all nodes of my cluster.

Any help would be appreciated.

Hi,

Loic

+7
java mongodb
source share
3 answers

Like still some people who come to this problem and try to answer, I myself answer it.

The problem no longer arises, I'm not sure why. Now I am updating my driver to version 2.12.3. No update on mongodb side.

Thanks for trying to help.

+1
source share

Since the question is more than a year old, I will use MongoDB 3.0 with the Java driver 3.0.4 for my solution.

Assume that there are 3 nodes (1 primary and 2 secondary) in the replica set (which is recommended the minimum number of nodes in the replica set) on ports 27017, 27018 and 27019, respectively. Therefore, I can create connections with the above configuration as follows:

 MongoClient mongo = new MongoClient(asList(new ServerAddress("localhost",27017), new ServerAddress("localhost", 27018), new ServerAddress("localhost", 27019), new MongoClientOptions.builder().requiredReplicaSetName("replset_name").build())); 

Note that using MongoClientOptions driver ensures that the above servers are indeed members of the specified replica set. You can skip this if you do not have a replica set.

During a crash, the driver will automatically switch to the new primary one automatically and start sending requests to it, but you must take care of the exceptions that were selected during CRUD operations .

+4
source share

We had the same problem. Updating the Mongo java driver to version 2.13.3 seems to fix the problem

0
source share

All Articles