简体   繁体   中英

MongoClient GetServer/GetDatabase best practise with ReplicaSet

When should I call MongoClient.GetServer() and MongoServer.GetDatabase() ?

Previously I was creating a single MongoDatabase instance at startup and using that for all operations. The problem is that when failover occurs, the primary becomes a different node, making the instance incorrect.

Should I call myClient.GetServer().GetDatabase(myDatabaseName) for every operation? This is probably the most correct, although some calls will fail during failover anyway. I'm tempted to reuse the same database instance for at least a group of operations.

My main concern is that calling GetServer() and GetDatabase() frequently will introduce overhead. I'm sure the driver will use the connection pool and hope that it will do caching of instances, but I do not know when it will have to talk to the server.

You should have one MongoClient representing your abstract connection to the database, one GetServer() call to instantiate a MongoServer instance with a given set of options, and one GetDatabase() call to instantiate a MongoDatabase instance. For the same set of options, you shouldn't need multiple instance of these objects.

It seems like the root cause of this question is failover hndling. The driver should discover the whole replica set and connect to the primary automatically. When failover occurs, there's a period where there is no primary as the election happens, but then the driver should connect to the new primary and resume normal operation. Your client code should be able to handle the failover period, in whatever way is appropriate for your application. The failover won't invalidate your MongoClient , MongoServer , or MongoDatabase instances.

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