Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MongoDb with Java Servlet

I am facing an issue with using Mongo DB on a Java servlet.

My servlet has many methods(~20) of accessing the database for retrieving and adding data. A very brief example of one :

public static String getSomething(String s) {
  String json = "[]";
  JSONArray jsonArray = new JSONArray();
  DBCollection table;

  try {
    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB( "myDb" );  
        BasicDBObject quoteQuery = new BasicDBObject("abc", abc);
    DBCursor cursor = table.find(quoteQuery);

    try {
      while(cursor.hasNext()) {
        jsonArray.put(cursor.next());
      }
    } finally {
      cursor.close();
    }

// ...

Now the problem is when this Java servlet is deployed in the linux server, it works fine for 10 days or so.

After that it crashes.

When I go to mongodb.log in my var/log directory I get the following repetitive output:

"connection refused because too many open connections"

I am not sure on where to edit things now or how to deal with this. I have tried to grow the limit of open connections in the server but still have the same results.

Any suggestions?

like image 897
and_apo Avatar asked Feb 27 '26 21:02

and_apo


1 Answers

from the API doc : http://api.mongodb.org/java/2.11.3/

public class Mongo extends Object

A database connection with internal connection pooling. For most applications, you should have one Mongo instance for the entire JVM.

like image 198
Frederic Close Avatar answered Mar 01 '26 09:03

Frederic Close