Spring Boot project application message server RabbitMQ (brief introduction)

1. Background

This chapter describes the application of the message server RabbitMQ when the user places an order

1.1 Application of message server

I am writing a small demo of an e-commerce project. In the e-commerce project, the application of the message server:

1. Order status notification: When the user places an order, the payment is successful, the order is shipped, the order is completed and other key nodes, the corresponding order status notification can be sent to the user through the message server.

2. Message push: Through the message server, personalized recommended products, promotional activities and other messages can be pushed to users to increase user participation and purchase rate.

3. Asynchronous processing: In some scenarios involving time-consuming operations, such as inventory deduction, logistics tracking, etc., the task can be handed over to the message server for asynchronous processing to improve the concurrency and response speed of the system.

4. Real-time chat: If your e-commerce system supports online customer service or real-time communication between users, the message server can be used to implement instant messaging.

5. Message queue: The message server can also serve as the carrier of the message queue to realize decoupling and asynchronous communication between different modules in the system.

The choice of message server can consider using open source message queue middleware, such as RabbitMQ, Apache Kafka, ActiveMQ, etc., or message queue services provided by cloud service providers, such as Alibaba Cloud's message queue RocketMQ, Tencent Cloud's message queue CMQ, etc.

It should be noted that when using a message server, ensure the security and reliability of the data, and reasonably design the format and transmission method of the message to ensure the normal operation of the system and user experience.

1.2 In the link of placing an order, the application scenario of the message server

When a user places an order, the application message server has the following common application scenarios:

1. Asynchronous order processing: After the user places an order, the order information can be sent to the message server, which will be processed asynchronously by the message server. This can reduce user waiting time and improve the concurrency of the system. The message server can be responsible for processing various business logic of the order, such as inventory deduction, generation of logistics order number and other operations.

2. Order status notification: After the user places an order, the notification server can send the order status notification to the user, such as the order has been submitted, the payment is successful, the order has been shipped, and the order has been completed. The message server can push notifications to users in real time to provide a good user experience.

3. Order status tracking: In the entire order life cycle, the message server can record and track the status changes of the order. When the user queries the order status, the latest order status information can be obtained through the message server to ensure the accuracy and real-time performance of the order status.

4. Message queue: The message server can be used as a component of the message queue to queue up order-related messages. In this way, the dependencies between the order module and other modules can be decoupled, and the stability and scalability of the system can be improved.

2. Download and installation of RabbitMQ

2.1 The official website address of RabbitMQ:

The official website address of RabbitMQ:

RabbitMQ: easy to use, flexible messaging and streaming — RabbitMQ

2.2. Install using brew

1. Installation

brew install rabbitmq

Installation result:

 The installation path of rabbitmq:

/opt/homebrew/opt/rabbitmq

2. Configure environment variables

vi ~/.bash_profile
export RABBIT_HOME=${PATH}:/opt/homebrew/opt/rabbitmq
export PATH=${PATH}:$RABBIT_HOME/sbin
source ~/.bash_profile


2.3 Start RabbitMQ


1. Run
rabbitmq-server in the foreground

2. Run
rabbitmq-server-detached in the background

3. View the running status
rabbitmqctl status

4. Start the web plugin
rabbitmq-plugins enable rabbitmq_management

5. Restart
rabbitmq-server restart

5. Close
rabbitmqctl stop

2.4. Access MQ


1. The browser address
http://localhost:15672/
The default user name and password are guest

Add user
rabbitmqctl add_user miaojiang 123

Set the user as an administrator
rabbitmqctl set_user_tags miaojiang administrator

Configure users to log in remotely to
rabbitmqctl set_permissions -p "/" miaojaing ".*" ".*" ".*"

View newly added accounts

rabbitmqctl list_users

View the permissions used
rabbitmqctl list_permissions -p /

3. Spring Boot project application RabbitMQ

3.1. Add Maven dependencies:

Add the RabbitMQ client library dependency to your project's pom.xml file

<!--AMQP依赖,包含RabbitMQ-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

3.2. Configure RabbitMQ connection:

Add RabbitMQ connection information in the Spring Boot configuration file (application.properties or application.yml).

application.properties:

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

 

Configure mq parameters in application.yml:

spring:
  rabbitmq:
    #设置RabbitMQ的IP地址
    host: localhost
    #设置rabbitmq服务器用户名
    username: guest
    #设置rabbitmq服务器密码
    password: guest
    #设置rabbitmq服务器连接端口
    port: 5672

3.3 Create a switch

custom switch name

Create an exchange called "myExchange"

package com.example.usermanagement.mq;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    /*
    使用 @Configuration 注解创建一个配置类,并通过 @Bean 注解创建了一个名为 declareExchange 的方法,用于声明创建交换机。请根据实际情况修改交换机名称、类型和持久化设置。
     */

    public static final String EXCHANGE_NAME = "myExchange";

    @Bean
    public Exchange declareExchange() {
        return ExchangeBuilder.directExchange(EXCHANGE_NAME)
                .durable(true)
                .build();
    }
}

3.4 Create a message sender

Create a message sender: Create a message sender class for sending messages to RabbitMQ

package com.example.usermanagement.mq;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessageSender{

    private final AmqpTemplate amqpTemplate;
    private final String exchangeName = "myExchange"; // 自定义交换机名称

    @Autowired
    public MessageSender(AmqpTemplate amqpTemplate) {
        this.amqpTemplate = amqpTemplate;
    }

    public void sendMessage(Object message) {
        amqpTemplate.convertAndSend(exchangeName, "", message); // 发送消息到默认交换机和空路由键
    }
}

Notice:

 The sendMessage type uses the Object type

3.5 RabbitMQ management background to add columns

step:

  1. Open a browser and enter the URL of the RabbitMQ management background. By default, the URL is http://localhost:15672/. Please make sure your RabbitMQ server is running and on the correct port number.

  2. Enter the username and password to log in to the RabbitMQ management background. By default, the username is guest, and the password is also guest. If you have changed your username and password, please log in with your custom credentials.

  3. After successfully logging in, you will see the main interface of the RabbitMQ management background. In the top navigation bar, choose QueuesTabs.

  4. On Queuesthe page, you will see a list of existing queues. If you want to create a new queue, click Add a new queuethe button.

  5. On the page to add a queue, fill in the following information:

    • Name: The name of the queue. Provide a unique name for the queue. (such as myQueue)
    • Durability: Persistence of the queue. Select Yes or No to specify whether the queue should persist across RabbitMQ service restarts.
    • Auto delete: Automatic deletion of the queue. Select Yes or No to specify whether to delete the queue when the last consumer disconnects.
    • Arguments: Additional parameters for the queue. This is optional, you can set some specific parameters for the queue.
  6. After filling out the queue information, click Add queuethe button to create the queue.

  7. After the creation is successful, you will Queuessee the newly added queue on the page. You can view the details of the queue on this page, including the number of messages, number of consumers, etc.

http://localhost:15672/#/queues

Just add the queue name 

 

3.6 Call the producer

1. Injection MessageSenderinstance

@Autowired
private MessageSender messageSender;

2. Call the method where the message needs to be sent messageSender.sendMessage. According to your business logic, you can call this method at an appropriate location. For example, after the order is successfully created, you can add the following code:

messageSender.sendMessage("订单已创建:" + order.getOrderId());

3.7 Create a message receiver

Create a message receiver: Create a message receiver class for processing received RabbitMQ messages.

Here we directly write the logic for processing RabbitMQ messages.

package com.example.usermanagement.mq;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class MessageReceiver {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("your_queue_name"),
            exchange = @Exchange(value = RabbitMQConfig.EXCHANGE_NAME)
//            key = "your_routing_key"
    ))
    public void receiveMessage(Object message) {
        System.out.println("Received message: " + message);
        // 处理消息逻辑
    }
}

Notice:

 The sendMessage type uses the Object type

your_queue_nameReplace with the name of the queue you want to listen to, (such as myQueue)

Replace your_routing_keywith the appropriate routing key (if used)

 

Guess you like

Origin blog.csdn.net/qq_39208536/article/details/132189312