简体   繁体   中英

Mongodb java driver cannot reconnect to primary after a crash

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

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 .

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.

We had the same problem. Upgrading the Mongo java driver to version 2.13.3 seems to solve the problem

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