Search in sources :

Example 6 with DetectResult

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();
        }
    }
}
Also used : DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) DetectResult(com.tencent.polaris.api.pojo.DetectResult) InetAddress(java.net.InetAddress) PolarisException(com.tencent.polaris.api.exception.PolarisException)

Aggregations

DetectResult (com.tencent.polaris.api.pojo.DetectResult)6 PolarisException (com.tencent.polaris.api.exception.PolarisException)2 ServiceUpdateRequest (com.tencent.polaris.api.plugin.registry.ServiceUpdateRequest)2 Instance (com.tencent.polaris.api.pojo.Instance)2 HashMap (java.util.HashMap)2 InstanceProperty (com.tencent.polaris.api.plugin.registry.InstanceProperty)1 ResourceFilter (com.tencent.polaris.api.plugin.registry.ResourceFilter)1 CircuitBreakerStatus (com.tencent.polaris.api.pojo.CircuitBreakerStatus)1 ServiceEventKey (com.tencent.polaris.api.pojo.ServiceEventKey)1 ServiceInstances (com.tencent.polaris.api.pojo.ServiceInstances)1 InstanceByProto (com.tencent.polaris.client.pojo.InstanceByProto)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 DatagramPacket (java.net.DatagramPacket)1 DatagramSocket (java.net.DatagramSocket)1 InetAddress (java.net.InetAddress)1 Socket (java.net.Socket)1 ArrayList (java.util.ArrayList)1 Map (java.util.Map)1