Build RabbitMQ messaging service and integrate SpringBoot to send and receive messages

Author's homepage : Designer Xiao Zheng
About the author : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, committed to enterprise digital transformation, CSDN blog expert, Blue Bridge cloud course certified instructor.

I. Introduction

1.1 What is message queue

Message queue is a communication mechanism for transferring data between applications . It is based on 发布-订阅a pattern and decouples message senders (publishers) and message receivers (subscribers) so that they can send and receive messages independently. .

In a message queue, the message sender sends the message to the queue, and the message receiver gets the message from the queue for processing . Message queue provides an asynchronous communication method, that is, the sender does not need to wait for the receiver's reply after sending the message, but can continue to perform other operations immediately. At the same time, the message queue can also implement persistent storage of messages to ensure the reliability of messages during the sending and receiving process.

The application scenarios of message queue are very wide, such as:

  • In a distributed system, message queues can be used to achieve decoupling between different modules;
  • In high-concurrency systems, message queues can be used to relieve system pressure;
  • In real-time data processing, the data can be stored in the message queue, and then processed by the data processing module.

Insert image description here

1.2 What is RabbitMQ

RabbitMQ is an open source message queuing middleware that implements the advanced message queuing protocol) and provides a reliable message delivery mechanism.

RabbitMQ is written in the Erlang language and is highly reliable, scalable, flexible and pluggable. It is widely used in distributed systems, microservice architecture, asynchronous task processing and other scenarios.

RabbitMQ works based on a producer and consumer model. Producers send messages to RabbitMQ's exchange, which then routes the messages to one or more queues, and consumers get the messages from the queues and process them.

RabbitMQ supports multiple messaging modes, and also provides message persistence, message priority, message confirmation mechanism and other features to ensure the reliability and reliable transmission of messages.

RabbitMQ is a mature and reliable message queue middleware that provides a powerful message delivery mechanism and rich features. It is widely used in distributed systems and asynchronous message processing.

Insert image description here

1.3 Why do you need to use RabbitMQ?

  1. Decoupling : RabbitMQ realizes the decoupling of producers and consumers through message queues. Producers send messages to the queue, and consumers get messages from the queue and process them. This decoupling enables different modules in the system to be developed and deployed independently, improving the flexibility and maintainability of the system.

  2. Asynchronous communication : RabbitMQ provides an asynchronous communication mechanism. After the producer sends a message to the queue, it does not need to wait for the consumer to process it immediately, but can continue to perform other operations. This asynchronous communication can improve the concurrency performance and response speed of the system.

  3. Buffering and Shaving : RabbitMQ can be used as a buffer to store messages from producers. This can avoid direct coupling between producers and consumers, and can also cope with instantaneous high concurrent requests and reduce system pressure.

  4. Reliability and recoverability : RabbitMQ provides the ability to persist messages so that messages can be retained and recovered even in the event of message queue or consumer failure. This reliability ensures that messages are not lost and delivered reliably.

  5. Scalability : RabbitMQ is an extensible message queue middleware that can add more message queues and consumer nodes when needed to cope with growing business needs.

  6. Multi-language support : RabbitMQ provides clients in multiple programming languages, such as Java, Python, C#, etc., allowing developers to choose their own programming language to interact with RabbitMQ.

Insert image description here

1.4 Advantages of RabbitMQ compared to Kafka

RabbitMQ provides a simple and easy-to-use API and management interface, allowing developers to quickly get started and configure and manage. In comparison, Kafka's configuration and management are relatively complex.

RabbitMQ supports multiple message delivery modes and message routing mechanisms, and can perform flexible message processing according to needs, while Kafka is more suitable for large-scale high-throughput streaming processing, usually using the publish-subscribe model.

RabbitMQ has features such as persistent messages and message confirmation mechanisms, which can ensure reliable transmission of messages, while Kafka provides highly reliable message delivery through multi-copy mechanisms and message logs.

RabbitMQ can perform flow control and peak shaving by setting the queue's current limiting policy and the consumer's consumption rate, which can protect consumers from excessive message push, while Kafka hands over the consumer's consumption rate control to the consumer itself, which may require additional processing in high concurrency scenarios.

RabbitMQ provides clients in multiple programming languages. Developers can choose the appropriate client for interaction based on their own programming needs. Kafka's clients are mainly focused on the Java language and have relatively little support for other languages.

RabbitMQ has a large open source community and rich ecosystem, providing a wealth of plug-ins and integration tools to facilitate developers to expand and integrate. Kafka's ecosystem is relatively small, but it has extensive applications and support in the field of big data.

Insert image description here


2. Set up the RabbitMQ environment

2.1 Install Erlang

Erlang is the basic environment of RabbitMQ messaging service, just like Java's JDK, it must be installed.

2.1.1 Download

Erlang official website download address: Download address .

Insert image description here

Because we need to install the RabbitMQ service on the server, students can download the Erlang installation package on the server, or download it and upload it to the server manually.

2.1.2 Installation

After the download is complete, double-click the installation package and follow the prompts to install it normally. The screenshot is shown below.

Insert image description here

Insert image description here

Insert image description here

Insert image description here

Insert image description here

2.1.3 Environment variable configuration

The variable name is as follows, and the variable value is the installation path, as shown in the figure below.

ERLANG_HOME

Insert image description here

Insert image description here

The verification command is as follows:

erl -v

Insert image description here

2.2 Install RabbitMQ

2.2.1 Download

RabbitMQ needs to be downloaded from Github, download address .

The RabbitMQ version needs to correspond to Erlang . This article installs 3.9.5the version.

2.2.2 Installation

The installation process is shown in the figure below.

Insert image description here

Insert image description here

Insert image description here

Insert image description here

2.2.3 Initialization

After the installation is complete, use the cmd window to enter the sbin directory of RabbitMQ, as shown in the figure below.

Insert image description here
Then enter the following command to complete the initial installation.

rabbitmq-plugins enable rabbitmq_management

Insert image description here

2.2.4 Verification

Open your browser and enter:

http://localhost:15672

The account password is:

guest

Insert image description here
Insert image description here

2.3 Configure external network access

2.3.1 Add new user

The default port of RabbitMQ is 15672, the username and password are both guest, and external access is not allowed.

So we need to add new users to achieve external network access. The operation process is as shown in the figure below.

Insert image description here

After clicking Add, enter the new user’s account and password, as shown in the figure below.

Insert image description here

2.3.2 Virtual Host configuration

Virtual Host needs to allow access to the added user, as shown in the figure below.

Insert image description here

After entering the sub-interface, select the user and submit, as shown in the figure below.

Insert image description here

Then, we completed the configuration of external network access.


3. Integrate RabbitMQ messaging service

3.1 Create a new SpringBoot project

Open the IDEA tool and create a new project, as shown in the figure below.

Insert image description here

After the new project is created, it is as shown in the figure below.

Insert image description here

3.2 Introducing dependencies

First, please pom.xmlintroduce dependencies in , the code is as follows.

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

3.3 Configuration file

application.yml is configured as follows.

spring:
  rabbitmq:
    host: 118.126.82.167
    port: 5672
    username: zwz
    password: 123456
    listener:
      simple:
        retry:
          enabled: true
          max-attempts: 5
          initial-interval: 2s

3.4 Create message sending tool class

Ask students to create SimpleProducera tool class with the following code.

package cn.zwz.send;

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

public class SimpleProducer {
    
    

    public static void main(String[] args) {
    
    
        //1. 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //1.1 设置连接IP
        connectionFactory.setHost("118.126.82.167");
        //1.2 设置连接端口
        connectionFactory.setPort(5672);
        //1.3 设置用户名
        connectionFactory.setUsername("zwz");
        //1.4 设置密码
        connectionFactory.setPassword("123456");
        //1.5 设置虚拟访问节点,就是消息发送的目标路径
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
    
    
            //2. 创建连接Connection
            connection = connectionFactory.newConnection("ZWZ-Connection");
            //3. 通过连接获取通道Channel
            channel = connection.createChannel();
            //4. 通过通道创建交换机,声明队列,绑定关系,路由key,发送消息,接收消息
            String queueName = "ZWZ-TOPIC";
            /**
             * channel.queueDeclare有5个参数
             * params1: 队列的名称
             * params2: 是否要持久化, false:非持久化 true:持久化
             * params3: 排他性,是否独占队列
             * params4: 是否自动删除,如果为true,队列会随着最后一个消费消费完后将队列自动删除,false:消息全部消费完后,队列保留
             * params5: 携带的附加参数
             */
            channel.queueDeclare(queueName, true, false, false, null);
            //5. 消息内容
            String message = "HELLO World!";
            //6. 将消息发送到队列
            channel.basicPublish("", queueName, null, message.getBytes());
            System.out.println("消息发送成功");
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            //7. 关闭通道
            if (channel != null && channel.isOpen()) {
    
    
                try {
    
    
                    channel.close();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
            //8. 关闭连接
            if (connection != null && connection.isOpen()) {
    
    
                try {
    
    
                    connection.close();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

3.5 Testing the message sending function

Sending a message is very simple, mainjust run the function.

Insert image description here

After the transmission is successful, the data can be received in the background, as shown in the figure below.

Insert image description here
Insert image description here

3.6 Create message receiving tool class

Ask students to create SimpleConsumera tool class with the following code.

package cn.zwz.send;

import com.rabbitmq.client.*;

import java.io.IOException;

public class SimpleConsumer {
    
    

    public static void work() {
    
    
        //1. 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //1.1 设置连接IP
        connectionFactory.setHost("118.126.82.167");
        //1.2 设置连接端口
        connectionFactory.setPort(5672);
        //1.3 设置用户名
        connectionFactory.setUsername("zwz");
        //1.4 设置密码
        connectionFactory.setPassword("123456");
        //1.5 设置虚拟访问节点,就是消息发送的目标路径
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
    
    
            //2. 创建连接Connection
            connection = connectionFactory.newConnection("ZWZ-Connection");
            //3. 通过连接获取通道Channel
            channel = connection.createChannel();
            //4. 通过通道创建交换机,声明队列,绑定关系,路由key,发送消息,接收消息
            String queueName = "ZWZ-TOPIC";
            //5. 接收消息并消费消息
            channel.basicConsume(queueName, true, new DeliverCallback() {
    
    
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
    
    
                    System.out.println("接收到的消息内容是:" + new String(message.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
    
    
                @Override
                public void handle(String consumerTag) throws IOException {
    
    
                    System.out.println("消息接收失败。。。");
                }
            });
            System.out.println("开始接受消息。。。。");
            //阻断程序
            System.in.read();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            //7. 关闭通道
            if (channel != null && channel.isOpen()) {
    
    
                try {
    
    
                    channel.close();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
            //8. 关闭连接
            if (connection != null && connection.isOpen()) {
    
    
                try {
    
    
                    connection.close();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

Then configure and run on the startup class, the code is as follows.

package cn.zwz.send;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SendApplication {
    
    

	public static void main(String[] args) {
    
    
		new SimpleConsumer().work();
		SpringApplication.run(SendApplication.class, args);
	}
}

3.7 Message receiving function test

Please run the SpringBoot startup class, and then send the message again, and you can see the message content, as shown in the figure below.

Insert image description here

4. Summary

This article first briefly introduces RabbitMQ, then compares it with popular message queues such as Kafka, and finally demonstrates the complete installation, configuration and integration process of RabbitMQ to help beginners get started with RabbitMQ development.


Insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132735972