search
HomeJavajavaTutorialWhat is the method for SpringBoot to integrate message queue RabbitMQ?

    Introduction

    In the Spring project, you can use Spring-Rabbit to operate RabbitMQ

    Especially in the spring boot project, you only need Just introduce the corresponding amqp starter dependency, conveniently use RabbitTemplate to send messages, and use annotations to receive messages.

    Generally during the development process:

    Producer project:

    • application.yml file configures RabbitMQ related information;

    • Write configuration classes in the producer project to create switches and queues, and bind them

    • Inject the RabbitTemplate object and send messages to the switch through the RabbitTemplate object

    Consumer Engineering:

    • application.yml file configuration RabbitMQ related information

    • Create message processing class , used to receive messages in the queue and process them

    Production end

    1. Create the producer SpringBoot project (maven)
    2. Introduction Start, dependency coordinates
    & lt; dependency & gt;
    & lt; group & gt; org.springFramework.Boot & LT;/Groupid & GT;
    & LT; ArtiFactid & GT; Spring-Boot-Starter-AMQP & LT;/Artifactid & GT;
    & LT; /dependency>

    3. Write yml configuration and basic information configuration
    4. Define configuration classes for switches, queues and binding relationships
    5. Inject RabbitTemplate, call methods, and complete message sending

    Add dependencies

    Modify the contents of the pom.xml file as follows:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.4.RELEASE</version>
        </parent>
        <groupId>com.itheima</groupId>
        <artifactId>springboot-rabbitmq-producer</artifactId>
        <version>1.0-SNAPSHOT</version>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-amqp</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
            </dependency>
        </dependencies>
    </project>

    Startup class

    package com.itheima.rabbitmq;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    @SpringBootApplication
    public class ProducerApplication {
        public static void main(String[] args) {
            SpringApplication.run(ProducerApplication.class);
        }
    }

    Configure RabbitMQ

    Configuration file

    Create application.yml with the following content:

    spring:
    rabbitmq:
    host: localhost
    port: 5672
    virtual-host: / itcast
    username: heima
    password: heima

    Bind switch and queue

    Create a configuration class for binding RabbitMQ queue and switch com.itheima.rabbitmq.config .RabbitMQConfig

    package com.itheima.rahhitmq.config;
    import org.springframework.amqp.core.*;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    @Configuration /// 配置类
    public class RabbitMQConfig {
        public static final String EXCHAGE_NAME = "boot_topic_exchange";
        public static final String QUEUE_NAME = "boot_queue";
        // 交换机
        @Bean("bootExchange")
        public Exchange bootExchange(){
            // 构建交换机对象
            return ExchangeBuilder.topicExchange(EXCHAGE_NAME).durable(true).build();
        }
        //Queue 队列
        @Bean("bootQueue")
        public Queue bootQueue(){
            return QueueBuilder.durable(QUEUE_NAME).build();
        }
        //队列和交换机的关系 Binding
        /**
         * 1 知道那个队列
         * 2 知道那个交换机
         * 3 routingKey
         */
        @Bean
        public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
            return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
        }
    }

    Build a consumer project

    Create a project

    Production end

    1. Create a producer SpringBoot project

    2. Introduce start, dependency coordinates

    org.springframework.boot

    spring-boot-starter-amqp

    Write yml configuration, basic information configuration
    Define switches, queues and The configuration class of the binding relationship
    Inject RabbitTemplate, call the method, and complete the message sending

    Add dependency

    Modify the content of the pom.xml file as follows:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.4.RELEASE</version>
        </parent>
        <groupId>com.itheima</groupId>
        <artifactId>springboot-rabbitmq-consumer</artifactId>
        <version>1.0-SNAPSHOT</version>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-amqp</artifactId>
            </dependency>
        </dependencies>
    </project>

    Start the class

    package com.itheima.rabbitmq;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    @SpringBootApplication
    public class ConsumerApplication {
        public static void main(String[] args) {
            SpringApplication.run(ConsumerApplication.class);
        }
    }

    Configure RabbitMQ

    Create application.yml with the following content:

    spring:
    rabbitmq:
    host: localhost
    port: 5672
    virtual-host: /itcast
    username: heima
    password: heima

    Message listening processing class

    Write message listener com.itheima.rabbitmq .listener.MyListener

    package com.itheima.rabbitmq.listener;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Component;
    @Component
    public class MyListener {
        /**
         * 监听某个队列的消息
         * @param message 接收到的消息
         */
        @RabbitListener(queues = "item_queue")
        public void myListener1(String message){
            System.out.println("消费者接收到的消息为:" + message);
        }
    }

    Test

    Create a test class in the producer project springboot-rabbitmq-producer and send the message:

    package com.itheima.rabbitmq;
    import com.itheima.rabbitmq.config.RabbitMQConfig;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.amqp.rabbit.core.RabbitTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class RabbitMQTest {
        @Autowired
        private RabbitTemplate rabbitTemplate;
        @Test
        public void test(){
            rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.insert", "商品新增,routing key 为item.insert");
            rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.update", "商品修改,routing key 为item.update");
            rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.delete", "商品删除,routing key 为item.delete");
        }
    }

    First run the above test program (switch and The queue can be declared and bound first), and then the consumer is started; check whether the corresponding message is received on the console in the consumer project springboot-rabbitmq-consumer.

    SpringBoot provides a way to quickly integrate RabbitMQ

    The basic information is configured in yml, the queue interactive machine and the binding relationship are configured using Beans in the configuration class

    Production The end directly injects RabbitTemplate to complete message sending

    The consumer end directly uses @RabbitListener to complete message receiving

    The above is the detailed content of What is the method for SpringBoot to integrate message queue RabbitMQ?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Why can't JavaScript directly obtain hardware information on the user's computer?Why can't JavaScript directly obtain hardware information on the user's computer?Apr 19, 2025 pm 08:15 PM

    Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

    Circular dependencies appear in the RuoYi framework. How to troubleshoot and solve the problem of dynamicDataSource Bean?Circular dependencies appear in the RuoYi framework. How to troubleshoot and solve the problem of dynamicDataSource Bean?Apr 19, 2025 pm 08:12 PM

    RuoYi framework circular dependency problem troubleshooting and solving the problem of circular dependency when using RuoYi framework for development, we often encounter circular dependency problems, which often leads to the program...

    When building a microservice architecture using Spring Cloud Alibaba, do you have to manage each module in a parent-child engineering structure?When building a microservice architecture using Spring Cloud Alibaba, do you have to manage each module in a parent-child engineering structure?Apr 19, 2025 pm 08:09 PM

    About SpringCloudAlibaba microservices modular development using SpringCloud...

    Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Apr 19, 2025 pm 08:06 PM

    Questions about a curve integral This article will answer a curve integral question. The questioner had a question about the standard answer to a sample question...

    What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?Apr 19, 2025 pm 08:03 PM

    In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

    Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Apr 19, 2025 pm 07:57 PM

    Why can't the main class be found after copying and pasting the package in IDEA? Using IntelliJIDEA...

    Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Apr 19, 2025 pm 07:54 PM

    State synchronization between Java multi-interface calls: How to ensure that interface A is called after it is executed? In Java development, you often encounter multiple calls...

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.