use of com.tencent.polaris.api.pojo.DetectResult in project polaris-java by polarismesh.
the class UdpHealthChecker method detectInstance.
@Override
public DetectResult detectInstance(Instance instance) throws PolarisException {
DatagramSocket socket = null;
try {
// TODO 从配置中读取
String sendStr = "detect";
InetAddress inet = InetAddress.getByName(instance.getHost());
byte[] sendBytes = sendStr.getBytes("UTF8");
socket = new DatagramSocket();
// 两秒接收不到数据认为超时,防止获取不到连接一直在receive阻塞
socket.setSoTimeout(2000);
// 发送数据
DatagramPacket sendPacket = new DatagramPacket(sendBytes, sendBytes.length, inet, instance.getPort());
socket.send(sendPacket);
byte[] recvBuf = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(recvPacket);
socket.close();
String expectRecvStr = "ok";
byte[] expectRecvBytes = expectRecvStr.getBytes("UTF8");
if (!Arrays.equals(Arrays.copyOfRange(recvBuf, 0, expectRecvBytes.length), expectRecvBytes)) {
return new DetectResult(RetStatus.RetFail);
}
return new DetectResult(RetStatus.RetSuccess);
} catch (Exception e) {
LOG.error("udp detect instance exception, host:{}, port:{}, e:{}", instance.getHost(), instance.getPort(), e);
return null;
} finally {
if (socket != null) {
socket.close();
}
}
}
Aggregations