我正在寻找检查Mongo DB连接的最佳方法。 情况:客户端向服务器发出请求(api)。服务器返回所有数据库的状态。
最好的方法是什么?
答案 0 :(得分:7)
我用这个:
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;
}
答案 1 :(得分: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
}
}
答案 2 :(得分:4)
ping命令是一个无操作,用于测试服务器是否响应命令。即使服务器处于写锁定状态,此命令也会立即返回:
import numpy as np
a = np.arange(16).reshape(4, 4).astype(float)
print (a)
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]
[ 12. 13. 14. 15.]]
il1 = np.tril_indices(4)
a[il1] = np.nan
print (a)
[[ nan 1. 2. 3.]
[ nan nan 6. 7.]
[ nan nan nan 11.]
[ nan nan nan nan]]
df = pd.DataFrame(data=a, columns=['a','b','c','d'])
print (df)
a b c d
0 NaN 1.0 2.0 3.0
1 NaN NaN 6.0 7.0
2 NaN NaN NaN 11.0
3 NaN NaN NaN NaN
答案 3 :(得分:2)
如果我正确理解您的问题,您希望通过Web服务调用返回状态。您可以编写一个调用db.serverStatus()
的函数并让它返回数据。查看文档:
答案 4 :(得分:1)
对Java使用MongoClient
,您需要的所有信息都在这里......
http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/