RabbitMQ學習(六):遠程結果調用
阿新 • • 發佈:2017-07-16
cells actor ble 隨機 get getenv all 求和 int
場景:我們需要在傳輸消息時得到結果
客服端在發送請求時會發送回調隊列,服務端處理事情完成後會將結果返回到回調隊列中,在增加關聯標誌關聯每個請求和服務返回
客戶端代碼:
public class RPCClient { factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); //聲明隊列 channel.queueDeclare(RPC_Queue_Name, false, false, false, null); //為每一個客戶端獲取一個隨機的回調隊列 //為每一個客戶端創建一個消費者(用於監聽回調隊列,獲取結果) QueueingConsumer consumer = new QueueingConsumer(channel); //消費者與隊列關聯 channel.basicConsume(replyQueueName, true, consumer); String response = null; String corrId = java.util.UUID.randomUUID //設置replyTo和correlationId屬性值 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 { |
RabbitMQ學習(六):遠程結果調用