zoukankan      html  css  js  c++  java
  • 第六篇:远程过程调用(RPC)

    Remote procedure call (RPC)

     

    1. 客户端接口
    2. 有关RPC的说明
    3. 回调队列
    4. 消息属性
    5. 关联的ID ( Correlation Id )
    6. 整合

    第二篇教程中,我们学习了如何使用工作队列在多个工作人员之间分配耗时的任务,但是如果我们需要在远程计算机上运行某个功能并等待结果呢?那么,这是一个不同的故事。这种模式通常称为远程过程调用RPC

    在本教程中,我们将使用RabbitMQ构建一个RPC系统:一个客户端和一个可扩展的RPC服务器。由于我们没有任何值得分发的耗时任务,我们将创建一个返回斐波那契数字的虚拟RPC服务。

    客户端接口

    为了说明如何使用RPC服务,我们将创建一个简单的客户端类。它将公开一个名为call的方法 ,它发送一个RPC请求并阻塞,直到收到应答:

    FibonacciRpcClient fibonacciRpc = new FibonacciRpcClient();
    String result = fibonacciRpc.call("4");
    System.out.println( "fib(4) is " + result);

    有关RPC的说明

    虽然RPC是计算中很常见的模式,但它经常受到批评。当程序员不知道函数调用是本地的还是慢速的RPC时会出现这些问题。像这样的混乱导致不可预测的系统,并增加了调试的不必要的复杂性,而不是简化软件,滥用RPC会导致不可维护的意大利面式代码。

    铭记这一点,请考虑以下建议:

    • 确保显而易见哪个函数调用是本地的,哪个是远程的。
    • 文件记录您的系统,使组件之间的依赖关系清晰。
    • 处理错误情况。当RPC服务器长时间关闭时,客户端应该如何反应?

    有疑问时避免使用RPC。如果可以的话,你应该使用异步管道 - 而不是类似于RPC的阻塞,结果被异步推送到下一个计算阶段。

    回调队列

    一般来说,通过RabbitMQ来实现RPC是很容易的。客户端发送请求消息,服务器回复响应消息。为了收到响应消息,我们需要在请求中发送一个“callback”队列地址。我们可以使用默认队列(在Java客户端中是独占的)。让我们试试看:

    callbackQueueName = channel.queueDeclare().getQueue();
    
    BasicProperties props = new BasicProperties
                                .Builder()
                                .replyTo(callbackQueueName)
                                .build();
    
    channel.basicPublish("", "rpc_queue", props, message.getBytes());
    
    // ... then code to read a response message from the callback_queue ...

    消息属性

    AMQP 0-9-1协议预先定义了消息的14个属性。大多数属性很少被使用,除了以下几点:

    • deliveryMode: 将消息标记为持久性(值为2)或瞬态(任何其他值)。您可能还记得第二个教程中的这个属性。
    • contentType: 用于描述编码的mime类型。例如,对于经常使用的JSON编码,将此属性设置为: application/json
    • replyTo: 通常用于命名回调队列。
    • correlationId: 有助于将RPC响应与请求关联起来

    依赖的类

    import com.rabbitmq.client.AMQP.BasicProperties;

    关联的ID ( Correlation Id )

    在上面介绍的方法中,我们建议为每个RPC请求创建一个回调队列。但是这是非常低效的,幸运的是有一个更好的方法 - 为每个客户端创建一个回调队列。

    这引发了一个新问题,该队列中收到回复后,不清楚回复属于哪个请求。这时就是使用correlationId属性的时候我们为每个请求设置一个唯一的correlationId值。稍后,当我们在回调队列中收到消息时,我们将查看此属性,并基于此属性,我们将能够将响应与请求进行匹配。如果我们看到未知的correlationId值,我们可以放心地丢弃该消息 - 它不属于我们的请求。

    您可能会问,为什么我们应该忽略回调队列中的未知消息,而不是因为错误参数的失败消息?这是由于服务器端可能出现竞争状况。虽然不太可能,但在发送给我们答案之后,但在发送请求的确认消息之前,RPC服务器可能会死亡。如果发生这种情况,重新启动的RPC服务器将再次处理该请求。这就是为什么在客户端,我们必须优雅地处理重复的响应,理想情况下RPC应该是幂等的。

    整合

    我们的RPC会像这样工作:

    • 当客户端启动时,它创建一个匿名独占callback队列。
    • 对于RPC请求,客户端会发送一条消息,其中包含两个属性: replyTo,它被设置为回调队列和correlationId,它被设置为每个请求的唯一值。
    • 该请求被发送到rpc_queue队列。
    • RPC worker(又名:服务器)正在等待该队列上的请求。当出现请求时,它执行该作业,并使用replyTo字段中的队列将结果发送回客户端
    • 客户端在回调队列中等待数据。当出现消息时,它会检查correlationId属性。如果它匹配来自请求的值,则返回对应用程序的响应。

     RPCClient.java

    package com.rabbitmq.tutorials.rpc;
    
    import com.rabbitmq.client.ConnectionFactory;
    import com.rabbitmq.client.Connection;
    import com.rabbitmq.client.Channel;
    import com.rabbitmq.client.DefaultConsumer;
    import com.rabbitmq.client.AMQP;
    import com.rabbitmq.client.Envelope;
    
    import java.io.IOException;
    import java.util.UUID;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.TimeoutException;
    
    public class RPCClient {
    
      private Connection connection;
      private Channel channel;
      private String requestQueueName = "rpc_queue";
      private String replyQueueName;
    
      public RPCClient() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.103");
    
        connection = factory.newConnection();
        channel = connection.createChannel();
    
        //为回复声明独占的“callback”队列。
        replyQueueName = channel.queueDeclare().getQueue();
      }
    
      //会生成实际的RPC请求
      public String call(String message) throws IOException, InterruptedException {
        final String corrId = UUID.randomUUID().toString();
    
        AMQP.BasicProperties props = new AMQP.BasicProperties
                .Builder()
                .correlationId(corrId)
                .replyTo(replyQueueName)
                .build();
    
        //发布具有两个属性的请求消息:  replyTo和correlationId
        channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
    
        //由于消费者交付处理是在另一个线程中执行,因此我们需要在响应到达之前暂停主线程。BlockingQueue是可能的解决方案之一。这里我们创建的 容量设置为1的ArrayBlockingQueue,
        // 因为我们只需要等待一个响应。
        final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
    
        //订阅'callback'队列,以便我们可以接收RPC响应
        channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
          @Override
          //该handleDelivery方法是做一个很简单的工作,对每一位消费响应消息它会检查的correlationID 是我们要找的人。如果是这样,它将响应BlockingQueue
          public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            if (properties.getCorrelationId().equals(corrId)) {
              response.offer(new String(body, "UTF-8"));
            }
          }
        });
        //从response中获取响应
        return response.take();
      }
    
      public void close() throws IOException {
        connection.close();
      }
    
      public static void main(String[] argv) {
        RPCClient fibonacciRpc = null;
        String response = null;
        try {
          fibonacciRpc = new RPCClient();
    
          System.out.println(" [x] Requesting fib(30)");
          response = fibonacciRpc.call("30");
          System.out.println(" [.] Got '" + response + "'");
        }
        catch  (IOException | TimeoutException | InterruptedException e) {
          e.printStackTrace();
        }
        finally {
          if (fibonacciRpc!= null) {
            try {
              fibonacciRpc.close();
            }
            catch (IOException _ignore) {}
          }
        }
      }
    }

     RPCServer.java

    package com.rabbitmq.tutorials.rpc;
    
    import com.rabbitmq.client.ConnectionFactory;
    import com.rabbitmq.client.Connection;
    import com.rabbitmq.client.Channel;
    import com.rabbitmq.client.Consumer;
    import com.rabbitmq.client.DefaultConsumer;
    import com.rabbitmq.client.AMQP;
    import com.rabbitmq.client.Envelope;
    
    import java.io.IOException;
    import java.util.concurrent.TimeoutException;
    
    public class RPCServer {
    
      private static final String RPC_QUEUE_NAME = "rpc_queue";
    
      /**
       * 斐波那契函数
       * @param n
       * @return
       */
      private static int fib(int n) {
        if (n ==0) return 0;
        if (n == 1) return 1;
        return fib(n-1) + fib(n-2);
      }
    
      public static void main(String[] argv) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.103");
    
        Connection connection = null;
        try {
          connection      = factory.newConnection();
          final Channel channel = connection.createChannel();
    
          channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
    
          channel.basicQos(1);
    
          System.out.println(" [x] Awaiting RPC requests");
    
          Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              AMQP.BasicProperties replyProps = new AMQP.BasicProperties
                      .Builder()
                      .correlationId(properties.getCorrelationId())
                      .build();
    
              String response = "";
    
              try {
                String message = new String(body,"UTF-8");
                int n = Integer.parseInt(message);
    
                System.out.println(" [.] fib(" + message + ")");
                response += fib(n);
              }
              catch (RuntimeException e){
                System.out.println(" [.] " + e.toString());
              }
              finally {
                channel.basicPublish( "", properties.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(envelope.getDeliveryTag(), false);
                // RabbitMq consumer worker thread notifies the RPC server owner thread 
                synchronized(this) {
                    this.notify();
                }
              }
            }
          };
    
          channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
          // 循环等待并准备消费RPC client发送的消息.
          while (true) {
              synchronized(consumer) {
                  try {
                      consumer.wait();//暂停主线程
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
        } catch (IOException | TimeoutException e) {
          e.printStackTrace();
        }
        finally {
          if (connection != null)
            try {
              connection.close();
            } catch (IOException _ignore) {}
        }
      }
    }

    执行步骤:

      1. 启动RPCServer.java
      2. 启动RPCClient.java实例3次






     全6篇完整项目地址:https://github.com/liwenzlw/rabbitmq-tutorials

  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    阿里巴巴的零知识证明
    DPOS委托权益证明 vs POW工作量证明
    DPOS共识算法 -- 缺失的白皮书
    信息图:股份授权证明机制(DPOS)
    DPOS——回归中本聪
    深度解析POS和POW的区别
  • 原文地址:https://www.cnblogs.com/jimboi/p/8457911.html
Copyright © 2011-2022 走看看