1. 程式人生 > >RabbitMQ學習(六):遠程結果調用

RabbitMQ學習(六):遠程結果調用

cells actor ble 隨機 get getenv all 求和 int

場景:我們需要在傳輸消息時得到結果

客服端在發送請求時會發送回調隊列,服務端處理事情完成後會將結果返回到回調隊列中,在增加關聯標誌關聯每個請求和服務返回

客戶端代碼:

public class RPCClient {
private final static String RPC_Queue_Name = "rpc_queue";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
ConnectionFactory factory = new

ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//聲明隊列
channel.queueDeclare(RPC_Queue_Name, false, false, false, null);

//為每一個客戶端獲取一個隨機的回調隊列
String replyQueueName = channel.queueDeclare().getQueue();
//為每一個客戶端創建一個消費者(用於監聽回調隊列,獲取結果)
QueueingConsumer consumer = new QueueingConsumer(channel);
//消費者與隊列關聯
channel.basicConsume(replyQueueName, true, consumer);

String response = null;
String corrId = java.util.UUID.randomUUID
().toString();

//設置replyTocorrelationId屬性值
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build();

//發送消息到rpc_queue隊列
channel.basicPublish("", RPC_Queue_Name, props, "8".getBytes());

while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
if (delivery.getProperties().getCorrelationId().equals(corrId)) {
response = new String(delivery.getBody(),"UTF-8");
break;
}
}
System.out.println( "fib(8) is " + response);
}
}

服務端代碼:

public class RPCServer {
private final static String RPC_Queue_Name = "rpc_queue";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel(); channel.queueDeclare(RPC_Queue_Name,false,false,false,null);
channel.basicQos(1);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(RPC_Queue_Name, false, consumer);
System.out.println(" [x] Awaiting RPC requests");
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
//獲取請求中的correlationId屬性值,並將其設置到結果消息的correlationId屬性中
BasicProperties props = delivery.getProperties();
AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder().correlationId(props.getCorrelationId()).build();
//獲取回調隊列名字
String callQueueName = props.getReplyTo();

String message = new String(delivery.getBody(),"UTF-8");

System.out.println(" [.] fib(" + message + ")");

//獲取結果
String response = "" + fib(Integer.parseInt(message));
//先發送回調結果
channel.basicPublish("", callQueueName, replyProps,response.getBytes());
//後手動發送消息反饋
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
}

private static int fib(int i)
{
if(i==0) return 0;
if (i==1) return 1;
return fib(i-1) +fib(i-2);
}
}

RabbitMQ學習(六):遠程結果調用