10

我正在寻找检查与 Mongo DB 的连接的最佳方法。情况:客户端向服务器发出请求(api)。服务器返回所有数据库的状态。

最好的方法是什么?

4

5 回答 5

8

我用这个:

Builder o = MongoClientOptions.builder().connectTimeout(3000);  
MongoClient mongo = new MongoClient(new ServerAddress("192.168.0.1", 3001), o.build());    

try {
  mongo.getAddress();
} catch (Exception e) {
  System.out.println("Mongo is down");
  mongo.close();
  return;
}
于 2015-11-17T13:25:12.340 回答
7

在 Java MongoDriver 3.3.0 中,使用 ServerMonitorListener 来确定服务器是否已启动和连接。这是示例代码,

public class ServerConnection implements ServerMonitorListener {
    private MongoClient client;

    public ServerConnection(){
        try {
            MongoClientOptions clientOptions = new MongoClientOptions.Builder()
                .addServerMonitorListener(this)
                .build();

            client = new MongoClient(new ServerAddress("localhost", 27017), clientOptions);
        } catch (Exception ex) {

        }
    }

    @Override
    public void serverHearbeatStarted(ServerHeartbeatStartedEvent serverHeartbeatStartedEvent) {
        // Ping Started
    }

    @Override
    public void serverHeartbeatSucceeded(ServerHeartbeatSucceededEvent serverHeartbeatSucceededEvent) {
        // Ping Succeed, Connected to server
    }

    @Override
    public void serverHeartbeatFailed(ServerHeartbeatFailedEvent serverHeartbeatFailedEvent) {
        // Ping failed, server down or connection lost
    }
}
于 2016-09-02T14:34:22.763 回答
6

ping 命令是用于测试服务器是否响应命令的无操作。即使服务器被写锁定,此命令也会立即返回:

        try{

            DBObject ping = new BasicDBObject("ping", "1");
            mongoTemplate.getDb().getMongo().getDB("DATABASE NAME"").command(ping);
        } catch (Exception exp){
            // MongoDb is down..
        }
于 2016-11-19T08:43:51.607 回答
2

Use MongoClient for Java, all the info you need is here...

http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

于 2013-06-19T14:50:09.787 回答
2

如果我正确理解您的问题,您希望通过 Web 服务调用返回状态。您可以编写一个调用db.serverStatus()并让它返回数据的函数。在此处查看文档:

监控 MongoDB

于 2013-06-19T14:52:18.420 回答