检查MongoDB服务器是否正在运行,凭据在Java中是否有效

我正在编写一个UI,用户应该可以在其中放入URL和端口来检查mongoDB服务器是否正在运行。 此外,他应该能够在必要时提供证书。

如果服务器没有运行或凭据错误,我想为每个案例提供一条消息。 这里回答了类似的问题:

使用Java 3.0驱动程序检查MongoDB身份validation

如何从驱动程序检查mongoDB服务器是否正在运行

不幸的是,他们使用旧版本的Java驱动程序用于mongo。 我正在使用3.2+版本的MongoDB java驱动程序,即不推荐使用getDB()。

我对这个问题的“解决方案”看起来有点像这样:

try { String database = "test"; MongoClient client = null; if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) { MongoCredential credentials = MongoCredential.createCredential(username, database, password.toCharArray()); client = new MongoClient(new ServerAddress(url, Integer.parseInt(port)), Arrays.asList(credentials)); } else { client = new MongoClient(url, Integer.parseInt(port)); } MongoDatabase db = client.getDatabase(database); db.listCollectionNames().first(); client.close(); return true; } catch (MongoCommandException | MongoSecurityException e) { // program does not get in here when credentials are wrong, // only when no credentials are provided, but necessary } catch (MongoSocketOpenException | MongoTimeoutException e) { // only get in here after db.listCollectionNames().first() caused a timeout } 

我该如何设法:

  1. 找出mongoDB服务器何时没有运行?
  2. 必要时发现凭据是否正确?

编辑:当凭据错误(用户名和/或密码)时,该方法仅捕获MongoTimeoutException 。 提供错误的URL或端口或数据库时也是如此。 要清楚的是,还有其他例外情况打印出来,但没有被抓住。 唯一的区别是,当提供无密码和没有用户名时,即使数据库需要它们, MongoCommandException捕获MongoCommandException