shjung 9 月之前
父节点
当前提交
6ed0046dff
共有 1 个文件被更改,包括 40 次插入0 次删除
  1. 40 0
      its-network/src/main/java/com/its/common/network/Network.java

+ 40 - 0
its-network/src/main/java/com/its/common/network/Network.java

@@ -0,0 +1,40 @@
+package com.its.common.network;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.*;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+
+@Slf4j
+public class Network {
+
+    private Network() {}
+
+    public static boolean isHostAlive(String host, int port, int retryCount, int timeoutSeconds) {
+        boolean result;
+        timeoutSeconds = Math.max(1, timeoutSeconds);
+        int timeoutMilliSeconds = timeoutSeconds * 1000;
+        int retry = 1;
+        do {
+            result = netCheck(host, port, timeoutMilliSeconds);
+            if (result) {
+                break;
+            }
+            log.info("Retry ping check[{}.{}: {}]", host, port, retry);
+        } while (++retry <= retryCount);
+        return result;
+    }
+
+    private static boolean netCheck(String host, int port, int timeoutMilliSeconds) {
+        try (Socket socket = new Socket()) {
+            socket.connect(new InetSocketAddress(host, port), timeoutMilliSeconds);
+            return true;
+        }
+        catch (IOException e) {
+            log.error("{}", e.getMessage());
+        }
+        return false;
+    }
+
+}