创建 mongodb 健康检查(在 dropwizard 中)

creating a mongodb healthcheck (in dropwizard)

不一定特定于 dropwizard,但对于我来说,我无法弄清楚如何轻松地为 mongodb 创建健康检查。这是在 java 中,使用 mongodb 自己的 java 驱动程序的 3.3.0 版。

我希望有一种方法在成功时不会改变数据库的状态,但在查询(或连接,或其他)失败时也会抛出异常,以便 return 健康或不健康的状态。理想情况下,我会执行 find,但据我所知,这不会引发异常。

我会像这样列出数据库中的所有集合:

MongoClient client = new MongoClient(addr, opts);
MongoDatabase db = client.getDatabase(database);
try {
    MongoIterable<String> allCollections = db.listCollectionNames();
    for (String collection : allCollections) {
        System.out.println("MongoDB collection: " + collection);
    }
} catch (Exception me) {
    // problems with mongodb
}