Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb java driver cannot reconnect to primary after a crash

Tags:

java

mongodb

I have an issue when trying the failover capacity of mongodb with the java driver.

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

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

When I re-start server1, it takes back it's primary role in a few seconds but then my application, instead of connecting to the server1 still tries to connect to server2 and, as it's now in secondary state failled! All the requests are failling with this error :

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

I am using a mongodb 2.6 and a java driver 2.12. I am not passing any parameter to my MongoClient that is created using all the nodes of my cluster.

Any help will be welcome.

Regards,

Loïc

like image 296
loicmathieu Avatar asked May 05 '14 09:05

loicmathieu


2 Answers

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

Suppose there are 3 nodes (1 primary and 2 secondary) in a replica set (which is recommended minimum no. of nodes in a replica set) on ports 27017, 27018 and 27019 respectively. So I can create a connections with the above config 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, the driver guarantee that the above servers are indeed members of the said replica set. You can skip this if you don't have a replica set.

During fail overs the driver will switch to the new primary automatically and start sending requests to it, but you have to take care of the exceptions thrown during CRUD operations.

like image 188
jayantS Avatar answered Sep 29 '22 15:09

jayantS


As there as still some people arriving at this issue and trying to answer I answer it myself.

The issue is no longer occurring, I'm not sure why. I now update my driver to the 2.12.3 version. No update on mongodb side.

Thanks for those who try to help.

like image 36
loicmathieu Avatar answered Sep 29 '22 15:09

loicmathieu