rabbitmq+java入门(六)远程调度

参考:http://www.rabbitmq.com/tutorials/tutorial-six-java.html

源码:https://github.com/zuzhaoyue/JavaDemo

远程过程调用(RPC)

(使用Java客户端)

先决条件

本教程假定RabbitMQ 在标准端口(5672上的本地主机安装并运行如果您使用不同的主机,端口或证书,则连接设置需要进行调整。

 

第二篇教程中,我们学习了如何使用工作队列在多个工作人员之间分配耗时的任务。

但是如果我们需要在远程计算机上运行某个功能并等待结果呢?这种模式通常称为远程过程调用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是很容易的。客户端发送请求消息,服务器回复响应消息。为了收到回复,我们需要发送一个接收队列的名字给server,可以使用之前用的随机队列(在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:

import com.rabbitmq.client.AMQP.BasicProperties;

correlation ID

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

以下【】里的一长串是官方解释,我感觉这么说要通俗一些:假设客户端和服务器端是两个特工:C和S,有一天C需要从S那取一些货,他们约定在巷子(队列)见面,但是巷子里有很多人,C怎么知道哪一个是特工S呢?于是聪明的C在之前和S对了暗号(correlationId ),能对上暗号的人自然就是要找的特工S啦,其他的人忽略就好~

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

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

概要

我们的RPC会像这样工作:

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

把它放在一起

斐波那契任务:

private  static  int  fib int n)  {  if(n == 0 return 0 ; if(n == 1return 1 ; return fib(n- 1)+ fib(n- 2); }
以上是
声明斐波那契函数。它只假定有效的正整数输入。(不要指望这个版本适用于大数字,它可能是最慢的递归实现,意思一下就好)。

我们的RPC服务器RPCServer.java的代码如下所示:

//package rmq.rpc;

/**
 * Created by zuzhaoyue on 18/5/18.
 */
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";

    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("localhost");

        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())//收到clent发给server的暗号,默默记下来再发回去
                            .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 {
                        //发回去啦,队列名是接收时指定的队列名properties.getReplyTo(),参数replyProps里带上corrid
                        String queueName = properties.getReplyTo();
                        System.out.println("===返回的队列名:" + queueName);
                        channel.basicPublish( "", queueName, replyProps, response.getBytes("UTF-8"));
                        long tag = envelope.getDeliveryTag();
                        System.out.println("===tag:" + tag);
                        channel.basicAck(envelope.getDeliveryTag(), false);//是否批量,true:一次性ack所有小于等于tag的消息,false:只ack index为tag的消息
                        // RabbitMq consumer worker thread notifies the RPC server owner thread
                        synchronized(this) {
                            this.notify();
                        }
                    }
                }
            };

            //消费rpc_queue里的任务
            channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
            // Wait and be prepared to consume the message from 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) {}
        }
    }
}

服务器代码非常简单:

  • 像往常一样,我们首先建立连接,通道并声明队列。
  • 我们可能想要运行多个服务器进程。为了在多个服务器上平均分配负载,我们需要在channel.basicQos中设置 prefetchCount为1
  • 我们使用basicConsume来访问队列,在那里我们以对象的形式提供回调(DefaultConsumer),该对象将完成工作并将响应发送回去。

以下是RPC客户端RPCClient.java的代码

//package rmq.rpc;

/**
 * Created by zuzhaoyue on 18/5/18.
 */
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("localhost");

        connection = factory.newConnection();
        channel = connection.createChannel();

        replyQueueName = channel.queueDeclare().getQueue();
    }

    public String call(String message) throws IOException, InterruptedException {
        final String corrId = UUID.randomUUID().toString();//声明一个暗号,接收server消息时暗号要对上才能接收

        AMQP.BasicProperties props = new AMQP.BasicProperties
                .Builder()
                .correlationId(corrId)
                .replyTo(replyQueueName)//声明一个接收地,让server往这个队列返回消息
                .build();

        //向server发送请求,请求消息发送给了队列replyQueueName,另外在props里加上了接收地replyQueueName和暗号corrId
        channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
        //用BlockingQueue来延缓main线程,1代表我们只需要一个response
        final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);

        //接收server返回的消息,对每一个收到的message都check一下corrid,相同的则put到BlockingQueue中
        channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
            @Override
            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"));
                }
            }
        });

        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) {}
            }
        }
    }
}

客户端代码稍有涉及:

  • 我们建立连接和通道,并为回复声明独占的“callback”队列。
  • 我们订阅'回调'队列,以便我们可以接收RPC响应。
  • 我们的调用方法会生成实际的RPC请求。
  • 在这里,我们首先生成一个唯一的correlationId 数并保存它 - 我们 在DefaultConsumer中handleDelivery的实现将使用这个值来捕获适当的响应。
  • 接下来,我们发布具有两个属性的请求消息: replyTocorrelationId
  • 在这一点上,我们可以坐下来等待,直到适当的响应到达。
  • 由于我们的消费者交付处理发生在单独的线程中,因此我们需要在响应到达之前暂停线程。用法的BlockingQueue是可能的解决方案之一。这里我们创建的 容量设置为1的ArrayBlockingQueue,因为我们只需要等待一个响应。
  • handleDelivery方法在做一个很简单的工作,对每一位消费响应消息它会检查的correlationID 。如果匹配,它将响应BlockingQueue
  • 同时线程正在等待响应从BlockingQueue中取得响应
  • 最后,我们将回复返回给用户。

提出客户要求:

RPCClient fibonacciRpc = new RPCClient();

System.out.println(" [x] Requesting fib(30)");
String response = fibonacciRpc.call("30");
System.out.println(" [.] Got '" + response + "'");

fibonacciRpc.close();

测试

1.编译

javac -cp /data/amqp-client-4.2.0.jar RPCServer.java 

2.执行

1)打开一个窗口,输入命令

java -cp /data/amqp-client-4.2.0.jar:/data/slf4j-api-1.7.21.jar:. RPCServer

这样我们的服务器已经准备就绪了

2)运行RPCClient.java的main发送消息

3)观察客户端和服务器端

服务器端:

客户端:

这样就实现了客户端请求,服务端处理并返回给客户端的rpc调用~调试成功。

猜你喜欢

转载自www.cnblogs.com/zuxiaoyuan/p/9056894.html