Table of Contents
Environment configuration
Message loss analysis
Production phase
The production end simulation message is lost
RabbitMQ
Consumer end
Home Java javaTutorial How to use SpringBoot+RabbitMQ to achieve reliable message transmission

How to use SpringBoot+RabbitMQ to achieve reliable message transmission

May 29, 2023 pm 10:34 PM
springboot rabbitmq

    Environment configuration

    SpringBoot Integration RabbitMQ realizes the sending of messages.

    1. Add maven dependencies

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter</artifactId>

     </dependency>

     

     <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-web</artifactId>

     </dependency>

     

     <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-amqp</artifactId>

     </dependency>

    Copy after login

    2. Add application.yml configuration file

    1

    2

    3

    4

    5

    6

    spring:

      rabbitmq:

        host: 192.168.3.19

        port: 5672

        username: admin

        password: xxxx

    Copy after login

    3. Configure switches, queues and bindings

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    @Bean

    public DirectExchange myExchange() {

        DirectExchange directExchange = new DirectExchange("myExchange");

        return directExchange;

    }

     

    @Bean

    public Queue myQueue() {

        Queue queue = new Queue("myQueue");

        return queue;

    }

     

    @Bean

    public Binding binding() {

        return BindingBuilder.bind(myQueue()).to(myExchange()).with("myRoutingKey");

    }

    Copy after login

    4. Production sends messages

    1

    2

    3

    4

    5

    6

    7

    8

    9

    @Autowired

    private RabbitTemplate rabbitTemplate;

     

    @GetMapping("/send")

    public String send(String message) {

        rabbitTemplate.convertAndSend("myExchange","myRoutingKey",message);

        System.out.println("【发送消息】" + message)

        return "【send message】" + message;

    }

    Copy after login

    5. Consumers receive messages

    1

    2

    3

    4

    5

    6

    @RabbitListener(queuesToDeclare = @Queue("myQueue"))

    public void process(String msg, Channel channel, Message message) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = new Date();

        String time = sdf.format(date);

        System.out.println("【接收信息】" + msg + " 当前时间" + time);

    Copy after login

    6. Call the production end to send messages hello, console output:

    [Send message] hello
    [Receive message] hello Current time 2022-05-12 10:21:14

    Indicates that the message has been successfully received.

    Message loss analysis

    How to use SpringBoot+RabbitMQ to achieve reliable message transmission

    From production to consumption of a message, message loss may occur in the following stages:

    • Lost on the production side: The producer cannot transmit to RabbitMQ

    • Lost on the storage side: RabbitMQ The storage itself is down

    • Lost at the consumer end: The storage cannot be sent to the consumer end due to network problems, or consumption hangs and normal consumption cannot be sent

    RabbitMQ Provides good support for reliable transmission from the production side, storage side, and consumer side.

    Production phase

    The production phase uses the request confirmation mechanism to ensure reliable transmission of messages. After sending a message to the RabbitMQ server, RabbitMQ receives the message and returns a request confirmation to the sender, indicating that the RabbitMQ server has successfully received the message.

    Configuration application.yml

    1

    2

    3

    4

    5

    6

    spring:

      rabbitmq:

        # 消息确认机制 生产者 -> 交换机

        publisher-confirms: true

        # 消息返回机制  交换机 -> 队列

        publisher-returns: true

    Copy after login

    Configuration

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    @Configuration

    @Slf4j

    public class RabbitConfig {

     

        @Autowired

        private ConnectionFactory connectionFactory;

     

        @Bean

        public RabbitTemplate rabbitTemplate() {

            RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

            rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

                @Override

                public void confirm(CorrelationData correlationData, boolean ack, String cause) {

                    log.info("【correlationData】:" + correlationData);

                    log.info("【ack】" + ack);

                    log.info("【cause】" + cause);

                    if (ack) {

                        log.info("【发送成功】");

                    } else {

                        log.info("【发送失败】correlationData:" + correlationData + " cause:" + cause);

                    }

                }

            });

            rabbitTemplate.setMandatory(true);

            rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {

                @Override

                public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

                    log.warn("【消息发送失败】");

                    log.info("【message】" + message);

                    log.info("【replyCode】" + replyCode);

                }

            });

     

            return rabbitTemplate;

        }

    }

    Copy after login

    Messages from producer to switch, there is confirmCallback Confirm mode. After the message is successfully sent, the message will call the method confirm(CorrelationData correlationData, boolean ack, String cause), and determine whether the message is successfully sent based on ack.

    Messages from switch to queue have returnCallback return mode.

    Send message product message The console output is as follows:

    [Send message]product message
    [Receive message]product message Current time 2022-05 -12 11:27:56
    [correlationData]:null
    [ack]true
    [cause]null
    [Send successfully]

    The production end simulation message is lost

    There are two solutions here:

    • Close the broker immediately after sending the message. The latter shuts down the network, but after the broker is closed, the console will always report an error and send the message. Also reported a 500 error.

    • Send non-existent switch:

    1

    2

    // myExchange 修改成 myExchangexxxxx

    rabbitTemplate.convertAndSend("myExchangexxxxx","myRoutingKey",message);

    Copy after login

    Result:

    [correlationData]:null
    【ack】false
    【cause】channel error; protocol method: #method(reply-code=404, reply-text=NOT_FOUND - no exchange 'myExchangexxxxx' in vhost '/', class-id =60, method-id=40)
    [Failed to send]

    When sending fails, you can retry the message

    The switch is correct and the queue that does not exist is sent:

    The switch receives the message and returns a success notification. The console output:

    [correlationData]:CorrelationData [id=7d468b47-b422-4523-b2a2-06b14aef073c]
    [ack ]true
    [cause]null
    [Send successfully]

    The switch did not find the queue and returned failure information:

    [Message sending failed]
    [message]product message
    [replyCode]312

    RabbitMQ

    Enable queue persistence, create queues and switchesThe default configuration is persistence of. First, set the queue and switch correctly, and modify the queue for consumption monitoring so that messages are stored in the queue.

    Modify the persistence of the queue to non-persistence:

    1

    2

    3

    4

    5

    @Bean

    public Queue myQueue() {

        Queue queue = new Queue("myQueue",false);

        return queue;

    }

    Copy after login

    After sending the message, the message is stored in the queue, and then restarts RabbitMQ, the message no longer exists.
    Set queue persistence:

    1

    2

    3

    4

    5

    @Bean

    public Queue myQueue() {

        Queue queue = new Queue("myQueue",true);

        return queue;

    }

    Copy after login

    After restarting, the messages in the queue still exist.

    Consumer end

    The consumer end starts by default ack Automatic confirmation mode. When the queue message is received by the consumer, it will be automatically deleted from the queue regardless of whether there is a message from the consumer end. news. Therefore, in order to ensure that the consumer can successfully consume the message, change the automatic mode to manual confirmation mode:

    Modify the application.yml file

    1

    2

    3

    4

    5

    6

    spring:

      rabbitmq:

        # 手动消息确认

        listener:

          simple:

            acknowledge-mode: manual

    Copy after login

    After consuming and receiving the message, manual confirmation is required:

    1

    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    Copy after login
    Copy after login

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    @RabbitListener(queuesToDeclare = @Queue("myQueue"))

    public void process(String msg, Channel channel, Message message) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = new Date();

        String time = sdf.format(date);

        System.out.println("【接收信息】" + msg + " 当前时间" + time);

        System.out.println(message.getMessageProperties().getDeliveryTag());

        try {

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (IOException e) {

            e.printStackTrace();

        }

     

    }

    Copy after login

    If not added:

    1

    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    Copy after login
    Copy after login

    Send two messages

    After the message is received, there is no confirmation and it is put back into the queue:

    How to use SpringBoot+RabbitMQ to achieve reliable message transmission

    Restart the project. After that, the messages in the queue will be sent to the consumer, but without ack confirmation, they will continue to be put back into the queue.

    After adding channel.basicAck, restart the project

    How to use SpringBoot+RabbitMQ to achieve reliable message transmission

    The queue message will be deleted

    basicAck The last parameter of the method multiple means deleting the previous queue.

    multiple is set to true, and all subsequent queues are cleared

    How to use SpringBoot+RabbitMQ to achieve reliable message transmission

    The above is the detailed content of How to use SpringBoot+RabbitMQ to achieve reliable message transmission. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot Article Tags

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to use RabbitMQ to implement distributed message processing in PHP How to use RabbitMQ to implement distributed message processing in PHP Jul 18, 2023 am 11:00 AM

    How to use RabbitMQ to implement distributed message processing in PHP

    How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

    How to build a reliable messaging app with React and RabbitMQ

    Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

    Comparison and difference analysis between SpringBoot and SpringMVC

    Using RabbitMQ in Go: A Complete Guide Using RabbitMQ in Go: A Complete Guide Jun 19, 2023 am 08:10 AM

    Using RabbitMQ in Go: A Complete Guide

    Application practice of go-zero and RabbitMQ Application practice of go-zero and RabbitMQ Jun 23, 2023 pm 12:54 PM

    Application practice of go-zero and RabbitMQ

    SpringBoot+Dubbo+Nacos development practical tutorial SpringBoot+Dubbo+Nacos development practical tutorial Aug 15, 2023 pm 04:49 PM

    SpringBoot+Dubbo+Nacos development practical tutorial

    Solution for real-time data synchronization between Golang and RabbitMQ Solution for real-time data synchronization between Golang and RabbitMQ Sep 27, 2023 pm 10:41 PM

    Solution for real-time data synchronization between Golang and RabbitMQ

    Golang RabbitMQ: Architectural design and implementation of a highly available message queue system Golang RabbitMQ: Architectural design and implementation of a highly available message queue system Sep 28, 2023 am 08:18 AM

    Golang RabbitMQ: Architectural design and implementation of a highly available message queue system

    See all articles