Search code examples
javamongodbmongo-java

Mongo Java connecting on invalid host/port, is it really connecting?


I have a following code

public class MongoService {

    private final Mongo mongo;
    private static final Logger LOGGER = LoggerFactory.getLogger(MongoService.class);

    public MongoService() throws UnknownHostException {
        mongo = new Mongo("localhot", 2707);
        DB db = mongo.getDB("contract");
        LOGGER.info(db.getCollection("Test").getName());
    }

    public Mongo getMongoInstance() {
        return mongo;
    }

    public void insert() {
        LOGGER.info("will run mongo insert now");
    }

    public void query() {
        LOGGER.info("will run query now");
    }

    public static void main(String args[]) throws UnknownHostException {
        MongoService mongoService = new MongoService();
        mongoService.insert();
        mongoService.query();

    }
}

Output

15:26:07.509 [main] INFO  c.s.s.business.persist.MongoService - Test
15:26:07.514 [main] INFO  c.s.s.business.persist.MongoService - will run mongo insert now
15:26:07.514 [main] INFO  c.s.s.business.persist.MongoService - will run query now
  • The host(should be localhost) and port(should be 27017) is clearly wrong, but when I run this program, it runs and doesn't gives any exceptions

  • Is it really connecting?? I am sure no, then how to handle such situations?


Solution

  • mongo.getDB("contract") simply creates a DB Object and put it into mongo-java-driver internal cache.

    AFAIK, a connection is obtained from the pool only when a request (ie. an operation as find, insert, ...) is sent to the database.

    Try to execute a findOne operation and an IOException should occur :

    java.io.IOException: couldn't connect to [/127.0.0.1:2017] bc:java.net.ConnectException: Connection refused
        at com.mongodb.DBPort._open(DBPort.java:228)
        at com.mongodb.DBPort.go(DBPort.java:112)
        at com.mongodb.DBPort.go(DBPort.java:93)
        at com.mongodb.DBPort.findOne(DBPort.java:146)
        at com.mongodb.DBPort.runCommand(DBPort.java:157)
        at com.mongodb.DBTCPConnector.fetchMaxBsonObjectSize(DBTCPConnector.java:457)
        at com.mongodb.DBTCPConnector.checkMaster(DBTCPConnector.java:444)
        at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:209)
        at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:305)
        at com.mongodb.DBCollection.findOne(DBCollection.java:647)
        at com.mongodb.DBCollection.findOne(DBCollection.java:626)
        at com.mongodb.DBCollection.findOne(DBCollection.java:615)