MongoDB - Java | How to manage the connection

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I am using MongoDB with Java and have some problems and questions about my connection. First of all, how should I connect to Mongo? Should I use a static client and leave it open? Because it takes like 500ms to connect. So it isn't the best idea to always connect it when users want data, is it?

But the next problem is following. When I do some querys i get the error message java.lang.IllegalStateException: The pool is closed or java.lang.IllegalStateException: state should be: open.

So, how should I manage my whole MongoDB connection stuff? Always wait 500ms is way to slow and restart the server after like 10 connections isn't that good. Are there any other good ways?

Thank you for your help!

回答1:

how should I connect to Mongo?

As it sounds, you're already using MongoClient, its a good way to go.

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.

Should I use a static client and leave it open?

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.

Do I need to explicitly close connection?

No, you don't. And that as well should resolve the error that you're getting.

Here is a Quick Tour on making the connection using MongoClient.



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