0
MongoClient m = new MongoClient(new ServerAddress("182.178.0.29",27017), 
        Arrays.asList(MongoCredential.createCredential("username", "employeedb", "password".toCharArray())));
MongoDatabase md = m.getDatabase("employeedb");
MongoIterable<String> strings = md.listCollectionNames();
MongoCursor<String> iterator = strings.iterator();  

After authentication i need to show message to end user. But, the exception is comming after 30 seconds in case when the user enters wrong credentials.User needs to wait untill the msg dialog comes. Could you please check why it is taking that much time and is there any other way to authenticate.

MongoDB version: 3.2.14 java driver version: 3.2.1

Exception:

com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector

Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
Srinivas
  • 147
  • 1
  • 14
  • Are you able to connect to `mongod` from mongo client? – harshavmb Sep 13 '17 at 10:17
  • I suspect it is a network issue. Timeout could be from `182.178.0.29` on `27017` port. You should try to connect to the above ip using telnet from machine which is running java program. Try running `ping` and `telnet` commands – harshavmb Sep 13 '17 at 10:19
  • I am able to connect from putty – Srinivas Sep 13 '17 at 10:22
  • How about telnet? Is 27017 port opened? – harshavmb Sep 13 '17 at 10:22
  • yes port 27017 is opened and i am able to get the data also from mongodb. – Srinivas Sep 13 '17 at 10:25
  • As part of the debugging I suggest connecting to that server from CLI using mongo client and "db address". Then reuse the very same address to initialise MongoClient with com.mongodb.MongoClientURI#MongoClientURI(java.lang.String) – Piohen Sep 13 '17 at 10:37
  • Please take a look at this https://stackoverflow.com/questions/30455152/check-mongodb-authentication-with-java-3-0-driver – s7vr Sep 13 '17 at 19:21

1 Answers1

0

If you know why your authentication is failing ( you mentioned wrong credentials) , then you can customize the timeout period for failing authentication using serverSelectionTimeout property so that you can show your users the failed authentication rather quickly. More explanation can be seen on MongoDB site here.

The serverSelectionTimeoutMS variable gives the amount of time in milliseconds that drivers should allow for server selection before giving up and raising an error. Users can set this higher or lower depending on whether they prefer to be patient or to return an error to users quickly (e.g. a "fail whale" web page). The default is 30 seconds, which is enough time for a typical new-primary election to occur during failover.

Shailendra
  • 8,874
  • 2
  • 28
  • 37