如何使用套接字创建简单的Java负载均衡器?

时间:2017-09-13 14:37:20

标签: java sockets udp

运行UDP Sever,监听多个端口,就像这个

一样简单
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(new UDPServer(9998));
executorService.execute(new UDPServer(9999));
// UDP server implementation
try (DatagramSocket socket = new DatagramSocket(port)) {
    System.out.println("Plain UDP server :" + this.port + " name :" + Thread.currentThread().getName());
    int numberOfPacketsReceived = 0;
    while (true) {
        // todo check to stop the server
        byte[] buffer = new byte[1024];
        DatagramPacket incomingDatagramPacket = new DatagramPacket(buffer, buffer.length);
        try {
            socket.receive(incomingDatagramPacket);
            System.out.println(Thread.currentThread().getName() + ":" + numberOfPacketsReceived++);
        } catch (IOException e) {
            e.printStackTrace();
            continue;
        }
    }
} catch (SocketException e) {
    e.printStackTrace();
}

我们可以创建一个以编程方式监听端口的负载均衡器  9997并将数据包转发到端口9999/9998?

我们甚至可以将一个UDP套接字中收到的流量重定向到另一个UDP套接字  另一个插座?

1 个答案:

答案 0 :(得分:-1)

最好让工作人员从阻塞队列中获取,并让第三个线程只读入数据包并将它们放在队列中以计算值。

您可以将数据包重定向到另一个套接字,但这会在同一个程序中产生不必要的开销,并且您将丢失数据包元数据。

如果您希望使用负载均衡器,可以像这样实现负载均衡器:

class C {
  public static void main(final String... args) {
    try (DatagramSocket socket = new DatagramSocket(9997);
         DatagramSocket out = new DatagramSocket()) {

      final InetSocketAddress[] sockets = {
          new InetSocketAddress("localhost", 9998),
          new InetSocketAddress("localhost", 9999)
      };

      int i = 0;
      while (true) {
      // todo check to stop the server
        byte[] buffer = new byte[1024];
        DatagramPacket incomingDatagramPacket = new DatagramPacket(buffer, buffer.length);
        try {
          socket.receive(incomingDatagramPacket);
          incomingDatagramPacket.setSocketAddress(sockets[i++%2]);
          out.send(incomingDatagramPacket);
        } catch (IOException e) {
          e.printStackTrace();
          continue;
        }
      }
    } catch (SocketException e) {
      e.printStackTrace();
    }
  }
}