1.模型图
实现过程:rpc称为远程过程调用。其过程简单理解为客户端去调用远程服务器的某个功能,将所需要的数据传递过去,远程服务器接受到数据后去实现该功能,并把该功能的结果再返回给客户端去处理,可以实现跨语言。
2.代码展示
客户端
public class Client{
public static void main(String[] args) throws IOException {
// 获取连接
Connection connection = MqUtil.getConnection();
// 创建通道
final Channel channel = connection.createChannel();
// 声明一个队列:客户端向服务器发送数据的队列
channel.queueDeclare("rpc",true,false,false,null);
// 也是声明一个队列,换了一种方式:服务器返回数据到客户端的队列
String replyQueueName = channel.queueDeclare().getQueue();
// 使用UUID随机生成一个id
final String correlationId = UUID.randomUUID().toString();
// 客户端发送给服务器添加的额外属性,详情可以看前面的basicPublish参数详解
AMQP.BasicProperties props = new AMQP.BasicProperties()
.builder()
.correlationId(correlationId)
.replyTo(replyQueueName)
.build();
// 客户端将数据发送到发送队列:参数是4,该数据携带了两个信息:correlationId和replyTo
channel.basicPublish("", "rpc", props,"4".getBytes());
// 客户端从相应队列获取到处理的结果
channel.basicConsume(replyQueueName,true,new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
// 通过correlationId去保证获取到的是正确的信息
if (properties.getCorrelationId().equals(correlationId)) {
// 处理的结果输出
System.out.println("测试" + new String(body));
}
// 关闭通道,注意一定要等结果返回后再关闭,不然拿不到返回的数据
MqUtil.close(channel,null);
}
});
// 最后关闭连接
MqUtil.close(null,connection);
}
}
服务器
public class Server {
public static void main(String[] args) throws IOException {
// 获取连接
Connection connection = MqUtil.getConnection();
// 创建通道
final Channel channel = connection.createChannel();
// 声明一个队列:客户端向服务器发送数据的队列
channel.queueDeclare("rpc",true,false,false,null);
// 消费发送队列里面的数据:获取到参数4
channel.basicConsume("rpc",true,new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
// 这个是获取到的参数4
String message = new String(body);
int n = Integer.parseInt(message);
// 带哦用服务器的一个功能,获取到结果
String fib = fib(n) + "";
AMQP.BasicProperties replyProps = new AMQP.BasicProperties
.Builder()
.correlationId(properties.getCorrelationId())
.build();
// 将结果返回会客户端,注意从properties去获取客户端传送过来的信息再返回回去
channel.basicPublish("", properties.getReplyTo(), replyProps, fib.getBytes());
}
});
}
private static int fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
}