How/where/when do I must call to MongoClient close?

廉价感情. 提交于 2021-02-08 03:02:56

问题


I am developing a web application in java and I have a doubt about closing MongoClient.

Seeing this http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads. See the concurrency doc page for more information. The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application. If for some reason you decide to create many MongoClient instances, note that: all resource usage limits (max connections, etc) apply per MongoClient instance to dispose of an instance, make sure you call MongoClient.close() to clean up resources

and this http://docs.mongodb.org/ecosystem/drivers/java-concurrency/#java-driver-concurrency

The Java MongoDB driver is thread safe. If you are using in a web serving environment, for example, you should create a single MongoClient instance, and you can use it in every request. The MongoClient object maintains an internal pool of connections to the database (default maximum pool size of 100). For every request to the DB (find, insert, etc) the Java thread will obtain a connection from the pool, execute the operation, and release the connection. This means the connection (socket) used may be different each time.

It seems that I must have an only instance of MongoClient. My doubt is: How/where/when do I must call to MongoClient close?

Thanks


回答1:


The API doc says:

"closes the underlying connector, which in turn closes all open connections. Once called, this Mongo instance can no longer be used. "

So, I would assume, that you only close it when you never want to open a MongoDB connection again (during this runtime). In other words, only at the end of the lifecycle of the application that uses this client instance.



来源:https://stackoverflow.com/questions/29165059/how-where-when-do-i-must-call-to-mongoclient-close

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!