Ajouve
Ajouve

Reputation: 10049

don't open a new connexion on each request mongodb java driver

I'm using a mongoDb database with java-ee

I have my connection object:

public class MongoDb {

static Mongo m;
DB db;
DBCollection coll;

public MongoDb(String collection){
    m = null;
    try {
        if(m==null){
            m = new Mongo( "127.0.0.1" );
        }
        db = m.getDB( "game" );
        coll = db.getCollection(collection);
    } catch (UnknownHostException e) {
        System.out.println("Database connexion error");
        e.printStackTrace();
    }
}

public void save(BasicDBObject bdbo){
    coll.insert(bdbo);
}

public void update(BasicDBObject search, BasicDBObject update){
    coll.update(search, update);
}

public void remove(BasicDBObject bdbo){
    coll.remove(bdbo);
}

public long count(){
    long nb = coll.getCount();
    return nb;
}

public List<DBObject> getAll(){
    List<DBObject> list = new ArrayList<DBObject>();
    DBCursor cursor = coll.find().limit(100);
    try {
       while(cursor.hasNext()) {
           list.add(cursor.next());
       }
    } finally {
       cursor.close();
    }
    return list;
}

public List<DBObject> getAll(String key, String value){
    List<DBObject> list = new ArrayList<DBObject>();
    BasicDBObject q = new BasicDBObject();
    q.append(key, Pattern.compile(value, Pattern.CASE_INSENSITIVE));
    DBCursor cursor = coll.find(q).limit(100);
    try {
       while(cursor.hasNext()) {
           list.add(cursor.next());
       }
    } finally {
       cursor.close();
    }
    return list;
}

public DBObject findOne(BasicDBObject bdbo){
    DBObject obj = coll.findOne(bdbo);
    return obj;
}
}

But each time I do a request this create a new connexion and there is a number max of connexion on mongodb, so if I reach the max number of request I have to restart mongodb

Is there a way to initialise the database connexion just one time, or to test id the connexion exits ?

Thanks

Upvotes: 0

Views: 325

Answers (1)

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33126

Yes, just don't reset the connection upon creation of the query object, do like this:

public class MongoDb {

static Mongo m = new Mongo("127.0.0.1");
DB db;
DBCollection coll;

public MongoDb(String collection){
    db = m.getDB( "game" );
    //...

Or redesign your classes to separate the database proxy (storing connection, maybe as a singleton) from the query objects.

Upvotes: 2

Related Questions