Have you ever heard of or used queues?

Have you ever heard of or used message queues?

Have you heard of or used RabbitMQ?

Now, these words, if you’ve used them, they might seem very simple to you, but if you haven’t used them, they might seem very complicated to you, at least until I started using them.

Well, this blog will cover message queuing, installation and configuration of the RabbitMQ environment, and finally a Hello World example to learn how to use RabbitMQ.

1. Basic concepts

1.1 the Queue (Queue)

A queue is one of the most common data structures. It is a special kind of linear table. It only allows delete operations at the front of the table and insert operations at the rear.

The end that inserts is called the end of the queue, and the end that deletes is called the end.

In Java, there is already a queue implementation under the java.util package that we can use directly.

1.2 Message Queue

A message is a unit of data passed between computers/applications and can be very simple, such as containing only text strings, or complex, such as containing embedded objects.

A message queue is a container that holds messages during their transmission.

When a message is transmitted, it is first sent to a queue. The main purpose of a queue is to provide routing and ensure the transmission of the message. If the receiver is unavailable, the message queue holds the message until it can be successfully delivered.

The message queue can be understood as an express company. You need to send an item (message) to your friend. The express company will ensure that the item will be delivered to your friend after receiving the item.

One wonders why we don’t just use the queue that comes with the JDK instead of using message queues.

This is because JDK queues are stored in memory, and messages are lost if the application or server fails. Using message queues can avoid message loss problems (note that it is not 100% lost), just like shipping companies guarantee that your items will be sent to your friends, but there is always a chance that they will be lost.

1.3 the RabbitMQ

RabbitMQ is a message queue middleware based on advanced Message Queuing Protocol (AMQP) developed in Erlang language.

It is widely used by Domestic Internet companies because it is open source and the version is updated quickly.

Other messaging-oriented middleware used include ActiveMQ, RocketMQ, Kafka, etc. If you are interested, you can study it yourself.

There are two more technical terms to know:

Producers: The application that sends the message is called a producer.

Consumer: The application that receives the message is called a consumer.

2. Install and configure RabbitMQ

With the basics out of the way, let’s install RabbitMQ on our machine, as it is based on the Erlang language, so we need to install Erlang first.

2.1 Erlang installation and configuration

Download Erlang from www.erlang.org/downloads

Because my computer is Windows 64-bit system, so I downloaded the 64-bit, the system is 32-bit students pay attention to the next version.

The installation process is relatively simple. The following are some screenshots:

After the installation is complete, you need to create a new environment variable (open method: Computer — right-click — Properties — Advanced System Settings — Advanced — Environment Variables) :

ERLANG_HOME E:\Program Files\erl10.4(change to your installation path)

2.2 RabbitMQ Installation and Configuration

RabbitMQ download: www.rabbitmq.com/install-win…

The installation process is also relatively simple. Here are some screenshots:

Once installed, run the following command in a CMD window to activate the RabbitMQ Manage Plugin

"E: \ \ Program Files \ the RabbitMQ Server \ rabbitmq_server - 3.7.15 \ sbin \ the RabbitMQ - plugins. Bat." " enable rabbitmq_management
Copy the code

Then run the command to restart the RabbitMQ service:

net stop RabbitMQ && net start RabbitMQ
Copy the code

If your CMD window is not opened as an administrator, the following error message is displayed

The solution is also very simple, as the administrator to open the CMD window to execute the command

Instead of using a command to restart the RabbitMQ service, open the Windows service list, find the RabbitMQ service, and restart it.

At this point, the RabbitMQ installation is complete, and there are a few default values to be aware of:

  • The default port number is 5672
  • The default user is guest guest
  • The default port number of the management background is 15672

Enter http://localhost:15672/ to view the RabbitMQ admin background and log in with the default guest account. From this background, you can create new users, configure user roles and create queues. There are also corresponding commands to complete the operation, about which I will write a separate blog later.

3. Hello World example

Now that the RabbitMQ environment is installed, let’s look at a simple example.

First in the POM file, add the dependency:

<dependency>
   <groupId>com.rabbitmq</groupId>
   <artifactId>amqp-client</artifactId>
   <version>5.7.0</version>
</dependency>
Copy the code

Producer creates a queue ‘Hello’ and sends a message ‘Hello World’ to the queue:

package com.zwwhnly.springbootaction.rabbitmq.helloworld;

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

import java.io.IOException;
import java.util.concurrent.TimeoutException;

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

    public static void main(String[] args) throws IOException, TimeoutException {
        // Create a connection
        ConnectionFactory factory = new ConnectionFactory();
        // Set the hostname of RabbitMQ
        factory.setHost("localhost");
        // Create a connection
        Connection connection = factory.newConnection();
        // Create a channel
        Channel channel = connection.createChannel();
        // Specify a queue. If no queue exists, it will be created automatically
        channel.queueDeclare(QUEUE_NAME, false.false.false.null);
        // Send a message
        String message = "Hello World!";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        // Close channels and connectionschannel.close(); connection.close(); }}Copy the code

Run the RabbitMQ admin and see that the queue has been created successfully and there is a message to consume:

Finally, we create a new Consumer class to consume this message:

package com.zwwhnly.springbootaction.rabbitmq.helloworld;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

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

    public static void main(String[] args) throws IOException, TimeoutException {
        // Create a connection
        ConnectionFactory factory = new ConnectionFactory();
        // Set the hostname of RabbitMQ
        factory.setHost("localhost");
        // Create a connection
        Connection connection = factory.newConnection();
        // Create a channel
        Channel channel = connection.createChannel();
        // Specify a queue
        channel.queueDeclare(QUEUE_NAME, false.false.false.null);
        // Create a queue consumer
        com.rabbitmq.client.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("Received Message '" + message + "'"); }}; channel.basicConsume(QUEUE_NAME,true, consumer); }}Copy the code

Running the code, we’ll see console output:

Received Message ‘Hello World! ‘

If you look in the RabbitMQ admin background, you will find that queue ‘hello’ has 0 messages to consume:

Do you think it is very simple, quickly try to install it on the machine!

4. Source code and reference

Source code address: github.com/zwwhnly/spr… Welcome to download.

Install rabbitMQ and common commands for operating rabbitMQ in Windows

【 例 】RabbitMQ: Hello World!