Reputation: 450
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!
Upvotes: 4
Views: 7415
Reputation: 31878
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.
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.
Upvotes: 5