Fork me on GitHub

RabbitMQ文档翻译——Hello World!(下)

Receiving

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.

译:这就是我们的消息发送者。我们的消息接收者是通过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接口的实现,我们用它来缓冲服务器推送给我们的消息。


 

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.

译:下面的设置与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.

译:注意,这里我们同样的声明一个消息队列。因为我们应该在开启发送者之前先开启接受者,我们需要确定在我们试图从消息队列中获取消息时,消息队列已经存在。


 

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.

译:我们将要告诉服务器可以从消息队列释放消息释放给我们了。之后它就会异步的将消息发送给我们,我们提供回调函数callback的形式缓冲消息,直到我们准备使用这些消息的时候。这就是DefaultConsumer做的事情。

在IDE中运行:

 

源码:

 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 }
View Code

 

posted @ 2016-09-11 15:58  郑斌blog  阅读(471)  评论(0编辑  收藏  举报