英文:
Is there a way to verify that mongodb is running in Java?
问题
目前我的应用程序使用MongoDB。如果在MongoDB未运行时发送请求,它将等待30秒钟,然后返回超时错误。我是否可以在启动应用程序时捕获到这种情况?
英文:
Currently my application uses MongoDB. If I send a request while mongo is not running it will wait 30 seconds before returning a Timeout Error. Is there a way that I can catch this while starting up my application?
答案1
得分: 0
以下是翻译好的内容:
最终选择了使用 Socket 进行连接测试:
public static void mongoIsConnected() throws Exception {
String mongoUrlStr = "http://localhost:27017"; // mongo 地址
URL mongoURL = new URL(mongoUrlStr);
SocketAddress socketAddress = new InetSocketAddress(mongoURL.getHost(), mongoURL.getPort());
Socket socket = new Socket();
socket.connect(socketAddress, 1000);
}
如果 MongoDB 未连接,将会抛出错误。
英文:
Ended up going with pinging the Socket:
public static void mongoIsConnected() throws Exception {
String mongoUrlStr = "http://localhost:27017"; // mongo url
URL mongoURL = new URL(mongoUrlStr);
SocketAddress socketAddress = new InetSocketAddress(mongoURL.getHost(), mongoURL.getPort());
Socket socket = new Socket();
socket.connect(socketAddress, 1000);
}
This will throw an error if mongo is not connected
答案2
得分: -2
你可以:
- 缩减服务器选择超时时间。有关相关的开发和生产配置指南,请参阅此处。
- 创建另一个具有较低服务器选择超时时间的客户端(例如1),并执行ping操作(使用运行命令助手发出
{ping:1}
)。这样,您将在1秒内知道部署是否已运行。
英文:
You can:
- Reduce the server selection timeout. See here for relevant development and production configuration guidance.
- Create another client with a low server selection timeout (e.g. 1) and perform a ping (issue
{ping:1}
using run command helper). This way you'll know within 1 second whether the deployment is up & running.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论