在RabbitMQ系列的第二篇文章Work Queus中,我们学会将耗时的task分布到多个workers。
那如果我们需要在一台远程电脑上执行一个函数然后等待获取结果?这种模式叫做Remote Procedure Call或者RPC。即远程程序调用。
这篇文章中我们将构建一个RPC系统:一个客户端和一个可伸缩的RPC服务器,我们将会构建一个返回计算斐波纳契结果的远程服务来模拟需要分布式的耗时task。
Client interface
我们通过客户端来调用远程服务,并阻塞等待结果的返回,调用代码如下
FibonacciRpcClient fibonacciRpc = new FibonacciRpcClient();
String result = fibonacciRpc.call("4");
System.out.println( "fib(4) is " + result);
Callback queue
一般来说,通过RabbitMQ来实现RPC比较简单,Client发生请求消息,Server返回应答消息,为了接收返回结果,我们需要在request里附带一个"callback" queue。可以使用默认的queue,代码如下
callbackQueueName = channel.queueDeclare().getQueue();
BasicProperties props = new BasicProperties
.Builder()
.replyTo(callbackQueueName)
.build();
channel.basicPublish("", "rpc_queue", props, message.getBytes());
Correlation Id
在上面的方法中,我们为每一个RPC requeest创建一个callback queue,这种效率比较低,我们可以为每个client创建一个callback queue。
这里面出现了一个新问题,当我们接收到response,我们不清楚这个response对应于哪个request,这时候就需要correlationId这个属性了。我们为每个request设置一个唯一值,当我们从callback queue接收到消息后,我们就可以根据这个值来匹配对于的request和response,当遇到一个不合理的correlationId值,我们就可以安全的丢弃这个消息。
你可能会疑惑为什么可以忽视在callback queue中未知的消息,而不是当作失败或者错误?这是由于server端的竞争条件导致的,虽然不太可能,RPC server可能在发送应答之后,在接受来自于request的确认消息之前挂掉,这种情况下,当RPC Server重启后,RPC Server会重新处理这个request,并再次发送应答,这就是客户端需要处理重复应答的原因。Rpc应该是幂等的。
rpc的模型如下
当client启动后,client创建一个匿名的callback queue。
对于一个rpc requset,client发送要给消息带有两个属性:replyTo设置为callback queue,correlationId设置为唯一值。
对于一个rpc server,等待来自于queue的requests,当一个request到来,处理request并将处理结果返回给client,这个queue来自于replyTo字段的值。
Client等待来自于callback queue的数据,当一个消息到来,检查correlationId属性,如果与request中相匹配,那就返回结果。
代码如下:
RPCServer.java
package org.rabbitmq;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
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");
factory.setPort(5673);
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);
// 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) {
}
}
}
}
RPCClient.java
package org.rabbitmq;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
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");
factory.setPort(5673);
connection = factory.newConnection();
channel = connection.createChannel();
replyQueueName = channel.queueDeclare().getQueue();
}
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();
channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
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) {
}
}
}
}
}
运行结果如下: