RabbitMQ官方文档翻译之Simple(一)

Introduction

Prerequisites(先决条件)

This tutorial assumes RabbitMQ is installed and running on localhost on standard port (5672). In case you use a different host, port or credentials, connections settings would require adjusting.

本教程假定RabbitMQ已在标准端口(5672)上的localhost上安装并运行。如果使用不同的主机,端口或凭据,下列代码中关于连接设置将需要调整。

RabbitMQ is a message broker: it accepts and forwards messages. You can think about it as a post office: when you put the mail that you want posting in a post box, you can be sure that Mr. Postman will eventually deliver the mail to your recipient. In this analogy, RabbitMQ is a post box, a post office and a postman.

RabbitMQ是一个消息代理:它接受并转发消息。 您可以将其视为邮局:当您将要把寄发的邮件投递到邮箱中时,您可以确信Postman 先生最终会将邮件发送给收件人。 在这个比喻中,RabbitMQ是一个邮箱,邮局和邮递员。

The major difference between RabbitMQ and the post office is that it doesn’t deal with paper, instead it accepts, stores and forwards binary blobs of data ‒ messages.

RabbitMQ和邮局之间的主要区别在于它不处理纸张,而是接受,存储和转发二进制数据块的消息。

RabbitMQ, and messaging in general, uses some jargon.

RabbitMQ和消息传递一般使用一些术语。

Producing means nothing more than sending. A program that sends messages is a producer :

生产意味着什么不仅仅是发送。 发送消息的程序是一个生产者:

image

A queue is the name for a post box which lives inside RabbitMQ. Although messages flow through RabbitMQ and your applications, they can only be stored inside a queue. A queue is only bound by the host’s memory & disk limits, it’s essentially a large message buffer. Many producers can send messages that go to one queue, and many consumers can try to receive data from one queue. This is how we represent a queue:

队列就像是在RabbitMQ中扮演邮箱的角色。 虽然消息流过RabbitMQ和您的应用程序,但它们只能存储在队列中。 队列只受主机的内存和磁盘限制的限制,它本质上是一个大的消息缓冲区。 许多生产者可以发送到一个队列的消息,许多消费者可以尝试从一个队列接收数据。 这是我们如何代表一个队列:

image

Consuming has a similar meaning to receiving. A consumer is a program that mostly waits to receive messages:

消费具有与接收相似的含义。消费者是主要是一个等待接收消息的程序:

image

Note that the producer, consumer, and broker do not have to reside on the same host; indeed in most applications they don’t.

请注意,producer,consumer和broker(rabbitMQ server)不必驻留在同一个主机上;确实在大多数应用程序中它们是这样分布的。

“Hello World”

(using the Java Client)

In this part of the tutorial we’ll write two programs in Java; a producer that sends a single message, and a consumer that receives messages and prints them out. We’ll gloss over some of the detail in the Java API, concentrating on this very simple thing just to get started. It’s a “Hello World” of messaging.

在本教程的这一部分,我们将用Java编写两个程序; 发送单个消息的生产者,以及接收消息并将其打印出来的消费者。 我们将介绍Java API中的一些细节,专注于这个非常简单的事情,只需要开始。 这是一个“Hello World”的消息传递。

In the diagram below, “P” is our producer and “C” is our consumer. The box in the middle is a queue - a message buffer that RabbitMQ keeps on behalf of the consumer.

在下图中,“P”是我们的生产者,“C”是我们的消费者。 中间的框是队列 - RabbitMQ代表消费者的消息缓冲区。

image

The Java client library

RabbitMQ speaks multiple protocols. This tutorial uses AMQP 0-9-1, which is an open, general-purpose protocol for messaging. There are a number of clients for RabbitMQ in many different languages. We’ll use the Java client provided by RabbitMQ.

Download the client library and its dependencies (SLF4J API and SLF4J Simple). Copy those files in your working directory, along the tutorials Java files.

Please note SLF4J Simple is enough for tutorials but you should use a full-blown logging library like Logback in production.

(The RabbitMQ Java client is also in the central Maven repository, with the groupId com.rabbitmq and the artifactId amqp-client.)

Java客户端库

RabbitMQ讲多种协议。 本教程使用AMQP 0-9-1,它是一种开放的通用的用于消息传递的协议。 有许多不同语言的RabbitMQ客户端。 我们将使用RabbitMQ提供的Java客户端。

下载客户端库及其依赖项(SLF4J API和SLF4J Simple)。 复制这些到你的工作目录中得仅仅是教程列举的java文件,依赖需要你自己添加。

请注意SLF4J 对于教程简单就足够了,但您应该使用成熟的日志库,如Logback。

(RabbitMQ Java客户端也位于Maven中央存储库中,groupId = com.rabbitmq 和 artifactId = amqp-client。)

Now we have the Java client and its dependencies, we can write some code.

现在我们有了java客户端和它的依赖,我们就可以写下面的代码

Sending (发送端)

image

We’ll call our message publisher (sender) Send and our message consumer (receiver) Recv. The publisher will connect to RabbitMQ, send a single message, then exit.

我们可以通知我们的消息发布者(发件人)发送和我们的消息消费者(接收者)Recv。发布商将连接到RabbitMQ,发送单个消息,然后退出。

In Send.java, we need some classes imported:

在Send.java中,我们需要一些导入的类

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

Set up the class and name the queue:

设置类并命名队列

public class Send {
  private final static String QUEUE_NAME = "hello";

  public static void main(String[] argv)
      throws java.io.IOException {
      ...
  }
}

then we can create a connection to the server:

那么我们可以创建一个到服务器的连接:

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

The connection abstracts the socket connection, and takes care of protocol version negotiation and authentication and so on for us. Here we connect to a broker on the local machine - hence the localhost. If we wanted to connect to a broker on a different machine we’d simply specify its name or IP address here.

Next we create a channel, which is where most of the API for getting things done resides.

To send, we must declare a queue for us to send to; then we can publish a message to the queue:

这个connection抽象的当做是套接字连接 socket connection,并对我们进行协议版本协商和认证等。 在这里,我们连接到本地机器上的代理 - 所以填localhost。 如果我们想连接到不同机器上的broker,我们可以在此处指定它的名称或IP地址。

接下来,我们创建一个通道channel,这是通过调用API完成大部分事情的的对象。

要发送,我们必须申明一个队列去存储我们要发送的消息;申明完后,我们就可以将消息发布到队列中:

channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");

Declaring a queue is idempotent - it will only be created if it doesn’t exist already. The message content is a byte array, so you can encode whatever you like there.

声明队列是幂等的 - 只有当它不存在时才会被创建。消息内容是一个字节数组,所以你可以编码你喜欢的任何东西。

Lastly, we close the channel and the connection;

最后,我们关闭通道和连接;

channel.close();
connection.close();

Here’s the whole Send.java class.

这是整个Send.java类。

Sending doesn’t work!

发送就不要再做其他的工作了

If this is your first time using RabbitMQ and you don’t see the “Sent” message then you may be left scratching your head wondering what could be wrong. Maybe the broker was started without enough free disk space (by default it needs at least 200 MB free) and is therefore refusing to accept messages. Check the broker logfile to confirm and reduce the limit if necessary. The configuration file documentation will show you how to set disk_free_limit.

如果这是您第一次使用RabbitMQ,并且没有看到“已发送”消息,那么您可能会很郁闷,可能认为他有错误。 或许是broker没有足够的可用磁盘空间启动(默认情况下至少需要200 MB),因此它拒绝接受message。 检查broker日志文件以确认并减少限制(如有必要)。 配置文件文档将显示如何设置disk_free_limit。

Receiving(接收)

That’s it for our publisher. Our consumer is pushed messages from RabbitMQ, so unlike the publisher which publishes a single message, we’ll keep it running to listen for messages and print them out.

上面说的就是publisher。消费者将接收到来自RabbitMQ推送的消息,它不同于发布单个消息的发布者,我们将保持它持续运行来监听消息并打印出来。
iamge
The code (in Recv.java) has almost the same imports as Send:
Recv.java 几乎和Send.java导入的jar包是一样的

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;

The extra DefaultConsumer is a class implementing the Consumer interface we’ll use to buffer the messages pushed to us by the server.

额外导入的DefaultConsumer是一个实现Consumer接口的类,用于缓冲由服务器推送给我们的消息

Setting up is the same as the publisher; 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.

代码也与publisher的相同;我们new一个连接和create一个通道,并声明我们要消费的队列。注意这里申明的队列要和发送的消息队列一致。

public class Recv {
  private final static String QUEUE_NAME = "hello";

  public static void main(String[] argv)
      throws java.io.IOException,
             java.lang.InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    ...
    }
}

Note that we declare the queue here, as well. Because we might start the consumer before the publisher, we want to make sure the queue exists before we try to consume messages from it.

请注意,我们也在这里声明队列并不是必须的。但是我们可能会在publisher之前启动消费者,所以我们要确保队列存在,然后再尝试从中消费消息

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.

我们还要告诉服务器将队列中的消息传递给我们。 由于它会异步地推送给我们的message,所以我们提供一个对象形式的回调,该对象将缓冲消息,直到我们准备好使用它们。 这是一个DefaultConsumer子类。

Consumer consumer = new DefaultConsumer(channel) {
  @Override
  public void handleDelivery(String consumerTag, Envelope envelope,
                             AMQP.BasicProperties properties, byte[] body)
      throws IOException {
    String message = new String(body, "UTF-8");
    System.out.println(" [x] Received '" + message + "'");
  }
};
channel.basicConsume(QUEUE_NAME, true, consumer);

Here’s the whole Recv.java class.(这里就是整个Recv.java)

Putting it all together

You can compile both of these with just the RabbitMQ java client on the classpath:

//把他们放在一起,我们可以在包含RabbitMQ java的类路径下编译它们 

javac -cp amqp-client-4.0.2.jar Send.java Recv.java
To run them, you'll need rabbitmq-client.jar and its dependencies on the classpath. In a terminal, run the consumer (receiver):

java -cp .:amqp-client-4.0.2.jar:slf4j-api-1.7.21.jar:slf4j-simple-1.7.22.jar Recv
then, run the publisher (sender):

java -cp .:amqp-client-4.0.2.jar:slf4j-api-1.7.21.jar:slf4j-simple-1.7.22.jar Send
On Windows, use a semicolon instead of a colon to separate items in the classpath.

The consumer will print the message it gets from the publisher via RabbitMQ. The consumer will keep running, waiting for messages (Use Ctrl-C to stop it), so try running the publisher from another terminal.

消费者将通过RabbitMQ打印从发布商获得的消息。消费者将继续运行,等待消息(使用Ctrl-C停止它),所以尝试从另一个终端运行发布者


Listing queues

You may wish to see what queues RabbitMQ has and how many messages are in them. You can do it (as a privileged user) using the rabbitmqctl tool:
您可能希望看到RabbitMQ有什么队列和其中有多少个消息。您可以使用rabbitmqctl工具(作为特权用户)

On Linux

sudo rabbitmqctl list_queues

On Windows, omit the sudo:

rabbitmqctl.bat list_queues

Time to move on to part 2 and build a simple work queue.

Hint

To save typing, you can set an environment variable for the classpath e.g.

>export CP=.:amqp-client-4.0.2.jar:slf4j-api-1.7.21.jar:slf4j-simple-1.7.22.jar
>java -cp $CP Send

or on Windows:

set CP=.;amqp-client-4.0.2.jar;slf4j-api-1.7.21.jar;slf4j-simple-1.7.22.jar
java -cp %CP% Send

http://www.rabbitmq.com/img/tutorials/producer.png

原文地址:https://www.cnblogs.com/chenny3/p/10226168.html