Java Driver - check if connection is successful

1,733 views
Skip to first unread message

Jesse Pinkelmann

unread,
Jul 26, 2016, 10:23:37 AM7/26/16
to mongodb-user
hello,

this is my connection. now when I dont start the mongo server, but execute the code, the MongoSocketOpenException wont be catched and first "Mongo established" appears and then a stacktrace of MongoSocketOpenException caused by ConnectException happens. How can I really check if the connection was successful? i'm using 3.2.2 sync driver java

if(client != null && !client.isLocked()) {
   
return false;
}
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
       
CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)),
        MongoClient.getDefaultCodecRegistry()
);
MongoClientOptions options = MongoClientOptions.builder().codecRegistry(codecRegistry)
       
.build();
MongoCredential credential = MongoCredential.createCredential(Flawbase.getTheConfig().getMongo().getUser(), "sexyMovies", Flawbase.getTheConfig().getMongo().getPw().toCharArray());
ServerAddress db = new ServerAddress(Flawbase.getTheConfig().getMongo().getIp(), Flawbase.getTheConfig().getMongo().getPort());
try {
   
client = new MongoClient(db, Collections.singletonList(credential), options);
    database = client.getDatabase("sexyMovies");
    test = database.getCollection("test");
    FlawlordUtils.log(Flawbase.getPluginName() + " Mongo established.");
} catch (MongoException e) {
   
System.out.println(Flawbase.getPluginName() + " Could not connect to mongo!");
    e.printStackTrace();
    return false;
}
return true;
Code hier eingeben...


Justin Lee

unread,
Jul 26, 2016, 10:36:59 AM7/26/16
to mongod...@googlegroups.com
You could use client.listDatabases() which would connect to the database immediately and error out on connection failure.

--------------------------------

name     : "Justin Lee", 
  title    : "Software Engineer",
  twitter  : "@evanchooly",
  web      : [ "mongodb.com", "antwerkz.com" ],
  location : "New York, NY" }

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: https://docs.mongodb.com/manual/support/
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/5310dc1b-6ad6-42fa-9491-4d80ae3d9f36%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages