As a common middleware in development, message queue is mainly used to deal with scenarios such as peak clipping, asynchronization and decoupling. RabbitMQ is widely used for its simplicity of use, flexibility in configuration, and ease of administration. In order to facilitate Xiaobai quick start, the course representative translated the official tutorial text for your reference, the following is its first: “Hello World”

1 “Hello World”

introduce

RabbitMQ is a Message Broker: it receives and forwards messages. You can think of it as a post office. When you put a letter in a mailbox, you can be sure that a mailman will finally deliver your letter to the recipient. In this analogy, RabbitMQ is a mailbox + post office + postman

The main difference between RabbitMQ and the post office is that it does not process paper mail. Instead, it receives, stores, and forwards binary data — messages.

RabbitMQ and message delivery use the following terms:

  • Producing produces means delivering. The program that sends the message is the producer:

  • Queues are the mailboxes in RabbitMQ. Although messages flow from RabbitMQ to your application, they can only be stored on a queue. The queue is limited by the memory and disk size of the host and is essentially a large message buffer. Producers can send messages to queues and consumers can receive messages from queues. The queue can be represented as follows:

  • Consuming is receiving messages. A consumer is a program waiting to receive a message:

Producer, consumer, and message broker do not have to be on the same host; in fact, in most application scenarios, they are all on different machines. An application can be either a producer or a consumer.

“Hello World”

(Java code implementation)

In this part of the tutorial, we’ll write two Java applications: a producer to send a single message, and a consumer to receive a message and print the received message. We’ll look at several Java APIs in detail to implement this simple functionality. This is the “Hello World” of messaging.

In the figure below, “P” is the producer, “C” is the consumer, and the red box in the middle is the queue — RabbitMQ’s message buffer for consumers.

Java library

RabbitMQ supports a variety of protocols, and this tutorial uses AMQP 0-9-1, an open source, general-purpose messaging protocol. RabbitMQ’s clients support a variety of programming languages. This article uses the Java client provided by Rabbtimq.

Download the appropriate Java libraries and associated dependencies (SLF4J API and SLF4J Simple). Copy the files to the working directory.

It is important to note that SLF4J Simple is only used for tutorial demonstrations, and production environments should use a full-featured logging library such as Logback

RabbitMQ’s Java client is also available in the Maven repository, groupId: com. rabbitMQ, artifactID: amqp-client.

Now that you have the Java client and the dependent libraries, it’s time to write some code.

Send (Sending)

We’ll name the sender class Send and the message receiver Recv. The publisher will connect to RabbitMQ, send a message, and exit.

In send.java, you need to introduce the following classes:

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

Write class code to name the queue:

public class Send { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { ... }}

Then connect to the server

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

The Connection class encapsulates the socket Connection and handles protocol version negotiation and authentication for us. Here we connect to the native RabbitMQ node — because the connection address is written as localhost.

If you want to connect to other machine nodes, you just need to specify the host name or IP address.

Next, you create a channel, on which all of the API’s work depends. Since both Connection and Channel implement java.io.Closeable, we can use the try-with-resource statement to prevent the explicit writing of closing code.

To send a message, declare a queue as the destination; The message is then sent to the queue, and all the code can be written to the try-with-resource statement

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 + "'");

Declare queue operations are idempotent — that is, they are created only if the declared queue does not exist. The message content is an array of characters, allowing you to encode arbitrary content.

Click to view the send.java source file

Receives (identifiers)

The above is about publishers. Our consumer listens for messages from RabbitMQ, and instead of a publisher sending a single message at a time, the consumer runs and listens for messages, and then prints out the messages it listens for.

References in recv.java are the same as Send:

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

We will use the DeliverCallback interface to cache the messages sent to us by the server.

The configuration code is the same as the publisher: Connection and channel are created, and the queue from which messages need to be consumed is declared. This is going to correspond to the publisher’s queue.

public class Recv { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { 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"); }}

Notice that we declared the queue here as well. Because we may run the producer before we run the publisher, we write this to ensure that the appropriate queue exists when consuming messages.

Why not use the try-with-resource statement to automatically close channels and connections? If you do this, you will simply let the program proceed, close all resources and exit the application! Our goal is to keep the application alive and continuously listen for messages asynchronously.

Next we will tell the server to send the message in the queue. Since the server pushes the message to us asynchronously, we provide a callback in the form of an object to cache the message until it is available. This is what the DeliverCallback subclass does

DeliverCallback deliverCallback = (consumerTag, delivery) -> {
    String message = new String(delivery.getBody(), "UTF-8");
    System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });

Click to view the recv.java source file

Code Integration: Putting It All Together

You can compile both files simply by placing the RabbitMQ Java client code under your classpath:

Javac-cp amqp-client-5.7.1.jar send.java recv.java

To run them, you need rabbitmq-client.jar and its dependency packages. To run a consumer receiver in a terminal:

Java - cp. : it - the client - 5.7.1. Jar: slf4j - API - 1.7.26. Jar: slf4j - simple - 1.7.26. Jar Recv

Then run the publisher:

Java - cp. : it - the client - 5.7.1. Jar: slf4j - API - 1.7.26. Jar: slf4j - simple - 1.7.26. Jar Send

On Windows, item delimiters in the classpath use semicolons instead of colons.

The consumer will print out the message published by the publisher, which is obtained through RabbitMQ. The consumer program will continue to run, waiting to receive a message (stop with Ctrl + C), so you can open a second terminal to run the sender.

List the queue

You might want to know what queues RabbitMQ has and how many messages are in each queue.

This can be viewed with the rabbitmqctl tool:

sudo rabbitmqctl list_queues

On Windows, omit sudo:

rabbitmqctl list_queues

Let’s move on to the second part, setting up a simple work queue.

tip

To shorten commands, you can set environment variables to these classpaths

Jar :slf4j-api-1.7.26. Jar :slf4j-simple-1.7.26. Jar :slf4j-simple-1.7.26. Jar :slf4j-simple-1.7.26

Windows:

set CP=.; It - the client - 5.7.1. Jar; Slf4j - API - 1.7.26. Jar; Slf4j -simple-1.7.26.jar ja-cp % cp % Send

Recommended reading

Freemarker Tutorial (1)- Template Development Manual

The downloaded attachment name is always garbled? It’s time you read the RFC documentation!


Code word is not easy, welcome thumb up share.

Search: 【The Java class representative】, pay attention to the public number, timely access to more Java dry goods.