有没有一种方法可以在Java中验证MongoDB是否正在运行?

huangapple go评论85阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月29日 05:50:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64110094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定