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. 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

在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
相关文章
相关标签/搜索