我正在寻找检查与 Mongo DB 的连接的最佳方法。情况:客户端向服务器发出请求(api)。服务器返回所有数据库的状态。
最好的方法是什么?
我用这个:
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;
}
在 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
}
}
ping 命令是用于测试服务器是否响应命令的无操作。即使服务器被写锁定,此命令也会立即返回:
try{
DBObject ping = new BasicDBObject("ping", "1");
mongoTemplate.getDb().getMongo().getDB("DATABASE NAME"").command(ping);
} catch (Exception exp){
// MongoDb is down..
}
Use MongoClient
for Java, all the info you need is here...
http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
如果我正确理解您的问题,您希望通过 Web 服务调用返回状态。您可以编写一个调用db.serverStatus()
并让它返回数据的函数。在此处查看文档: