Will
Will

Reputation: 6286

How to handle stale connections in MongoDB

What is the best way of automatically refreshing stale connections in Mongo?

After recycling the mongod service I get this exception from my Liferay Portlets:

com.mongodb.MongoException$Network: can't call something : /127.0.0.1:27017/connection_test

Upvotes: 2

Views: 4275

Answers (2)

Will
Will

Reputation: 6286

I ended up writing code that polls the connection before each DBCollection is requested.

private DBCollection safeColl(String pCollectionName, DBCollection pColl) {
    try {
        if (log.isDebugEnabled()) {
            log.debug("getting safe coll count on coll: " + pColl.getName());
        }
        pColl.count();
    } catch (MongoException e) {
        if (e.getMessage().startsWith("can't call something")) {
            pColl = getCollection(pCollectionName, true);
            return pColl;
        } else {
            throw e;
        }
    }
    return pColl;
}

Upvotes: 1

Sid
Sid

Reputation: 964

You need to have "handle the exception and retry logic" in your code. This might be of help : Exceptions, and how best to retry when a connection is reset?

Upvotes: 1

Related Questions