That's it for our sender. Our receiver is pushed messages from RabbitMQ, so unlike the sender which pushlishes a single message, we'll keep it running to listen for message and print them out. java
譯:這就是咱們的消息發送者。咱們的消息接收者是經過RabbitMQ的消息推送接收到消息,因此不一樣於消息發送者那樣只是簡單的發送一條消息,咱們須要保持它一直運行,就像一個監聽器同樣,用來不停的接收消息,並把消息輸出出來。服務器
The extra DefaultConsumer is a class implementing the Consumer interface we'll use to buffer the messages pushed to us by the server. 異步
譯:特別注意這個DefaultConsume,這個類是Consumer接口的實現,咱們用它來緩衝服務器推送給咱們的消息。async
Setting up is the same as the sender; we open a connection and a channel, and declare the queue from which we're going to consume. Note this matches up with the queue that send publishes to. ide
譯:下面的設置與sender差很少;咱們首先創建一個鏈接connection和一個通道channel,再聲明一個咱們要進行消費的消息隊列queue。注意這與發送到消息隊列相匹配。函數
Note that we declare the queue here, as well. Because we might start the receiver before the sender, we want to make sure the queue exists before we try to consume messages from it. this
譯:注意,這裏咱們一樣的聲明一個消息隊列。由於咱們應該在開啓發送者以前先開啓接受者,咱們須要肯定在咱們試圖從消息隊列中獲取消息時,消息隊列已經存在。spa
We're about to tell the server to deliver us the messages from the queue.Since it will push us messages asynchronously, we provide a callback in the form of an object that will buffer the messages until we're ready to use them. That is what a DefaultConsumer subclass does. code
譯:咱們將要告訴服務器能夠從消息隊列釋放消息釋放給咱們了。以後它就會異步的將消息發送給咱們,咱們提供回調函數callback的形式緩衝消息,直到咱們準備使用這些消息的時候。這就是DefaultConsumer作的事情。orm
1 package Consuming; 2 3 import com.rabbitmq.client.*; 4 5 import java.io.IOException; 6 7 /** 8 * Created by zhengbin06 on 16/9/11. 9 */ 10 public class Recv { 11 private final static String QUEUE_NAME = "hello"; 12 13 public static void main(String[] argv) 14 throws java.io.IOException, 15 java.lang.InterruptedException { 16 17 ConnectionFactory factory = new ConnectionFactory(); 18 factory.setHost("localhost"); 19 // factory.setPort(5672); 20 Connection connection = factory.newConnection(); 21 Channel channel = connection.createChannel(); 22 channel.queueDeclare(QUEUE_NAME, false, false, false, null); 23 System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 24 Consumer consumer = new DefaultConsumer(channel) { 25 @Override 26 public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) 27 throws IOException { 28 String message = new String(body, "UTF-8"); 29 System.out.println(" [x] Received '" + message + "'"); 30 } 31 }; 32 channel.basicConsume(QUEUE_NAME, true, consumer); 33 } 34 }