Closing MongoDB Java Connection

梦想与她 提交于 2019-12-04 07:20:57
jyemin

You should definitely not close the MongoClient every time you query the database. The MongoClient maintains a connection pool, which is relatively expensive to set up, so you'll want to re-use the MongoClient instance across the lifetime of your web application.

A couple of other things to point out:

  • There is a race condition in the connectToMongo method. You need to synchronize access to that method to ensure that at most one instance of MongoClient is ever created.
  • If you ever re-deploy your web application without first restarting your application server, you must ensure that the MongoClient is closed when your web application is shutdown. You can do that, for example, with a ServletContextListener.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!