Spring Boot 启动时自动配置 RabbitMQ 交换机、队列和绑定关系

在使用 Spring Boot 开发消息队列应用时,我们经常需要在应用启动时自动创建 RabbitMQ 的交换机、队列和绑定关系。本文将介绍如何通过 Spring Boot 的启动后执行方法来实现这一功能,并提供相应的演示代码和依赖配置。

一、添加依赖

为了在 Spring Boot 项目中使用 RabbitMQ,首先需要添加 RabbitMQ 的依赖。在 pom.xml 文件中添加以下依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

这个依赖引入了 Spring AMQP,简化了与 RabbitMQ 的集成。

二、配置 RabbitMQ

在 Spring Boot 的配置文件 application.propertiesapplication.yml 中,配置 RabbitMQ 的连接信息。以下是 application.yml 的配置示例:

yaml 复制代码
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

三、演示代码

以下是使用 @Configuration 注解、 @PostConstruct 注解、CommandLineRunner 接口和 ApplicationListener 接口来在 Spring Boot 启动时创建 RabbitMQ 交换机、队列和绑定关系的代码示例。

使用 @Configuration注解

java 复制代码
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Bean
    public Queue myQueue() {
        return new Queue("myQueue", true);
    }

    @Bean
    public TopicExchange myExchange() {
        return new TopicExchange("myExchange");
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(myQueue()).to(myExchange()).with("routingKey");
    }
}

使用 @PostConstruct 注解

java 复制代码
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RabbitMQConfig {

    @Autowired
    private ConnectionFactory connectionFactory;

    @PostConstruct
    public void init() {
        RabbitAdmin admin = new RabbitAdmin(connectionFactory);
        // 定义交换机
        admin.declareExchange(new TopicExchange("myExchange"));
        // 定义队列
        admin.declareQueue(new Queue("myQueue"));
        // 定义绑定关系
        admin.declareBinding(BindingBuilder.bind(new Queue("myQueue")).to(new TopicExchange("myExchange")).with("routingKey"));
    }
}

实现 CommandLineRunner 接口

java 复制代码
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
public class RabbitMQInitializer implements CommandLineRunner {

    @Autowired
    private ConnectionFactory connectionFactory;

    @Override
    public void run(String... args) throws Exception {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);

        // 定义交换机
        rabbitAdmin.declareExchange(new TopicExchange("myExchange"));
        // 定义队列
        rabbitAdmin.declareQueue(new Queue("myQueue"));
        // 定义绑定关系
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue("myQueue")).to(new TopicExchange("myExchange")).with("routingKey"));
    }
}

实现 ApplicationListener 接口

java 复制代码
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQApplicationListener implements ApplicationListener<ContextRefreshedEvent> {


    @Autowired
    private ConnectionFactory connectionFactory;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);

        // 定义交换机
        rabbitAdmin.declareExchange(new TopicExchange("myExchange"));
        // 定义队列
        rabbitAdmin.declareQueue(new Queue("myQueue"));
        // 定义绑定关系
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue("myQueue")).to(new TopicExchange("myExchange")).with("routingKey"));
    }
}

以上方法都可以在 Spring Boot 应用启动后自动配置 RabbitMQ 的交换机、队列和绑定关系,你可以根据实际需求选择合适的方法。希望这篇文章能帮助你更好地理解和应用 Spring Boot 与 RabbitMQ 的集成。

相关推荐
慧一居士5 分钟前
Kafka HA集群配置搭建与SpringBoot使用示例总结
spring boot·后端·kafka
uncofish36 分钟前
springboot不连接数据库启动(原先连接了mysql数据库)
数据库·spring boot·mysql
_BugMan41 分钟前
Spring Boot集成RocketMQ
spring boot·rocketmq·java-rocketmq
bing_1581 小时前
Spring Boot 应用中如何避免常见的 SQL 性能陷阱 (例如:SELECT *, NOT IN, 隐式类型转换)?
spring boot·sql·性能优化
yuanlaile1 小时前
Go全栈_Golang、Gin实战、Gorm实战、Go_Socket、Redis、Elasticsearch、微服务、K8s、RabbitMQ全家桶
linux·redis·golang·k8s·rabbitmq·gin
xbhog2 小时前
Java大厂面试突击:从Spring Boot自动配置到Kafka分区策略实战解析
spring boot·kafka·mybatis·java面试·分布式架构
bug菌2 小时前
面十年开发候选人被反问:当类被标注为@Service后,会有什么好处?我...🫨
spring boot·后端·spring
Java水解3 小时前
详细分析SpringBootTest中的测试类(附Demo)
spring boot·后端
阿杜杜不是阿木木4 小时前
03.使用spring-ai玩转MCP
java·人工智能·spring boot·spring·mcp·spring-ai
码熔burning4 小时前
【MQ篇】RabbitMQ之消息持久化!
java·分布式·rabbitmq·mq