SpringBoot集成RabbitMQ-Topic模式

本文介绍如何使用Spring Boot整合RabbitMQ实现消息队列的功能。通过示例代码展示了如何配置不同类型的交换机(Direct、Fanout、Topic),创建队列,并进行消息的发送与接收。特别关注了Topic交换机的使用及其路由键的匹配规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、POM配置文件

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

二、信息发送端

  配置所用的Bean ,接受端和这里一致

@Configuration
public class AmqpConfig {

    /*
    * Bean用于模拟Spring配置文件中的<bean>标签,
    * 用于创建名字为BootDirectExchange的交换机.
    **/
    /*@Bean
    public DirectExchange myChange(){
        return new DirectExchange("BootDirectExchange");
    }*/

    /*
    * 创建一个基于Fanout的交换机
    * 名字为BootFanoutExchange
    * */
    /*@Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange("BootFanoutExchange");
    }*/
    @Bean
    public Queue topicQueue(){
        return new Queue("topicQueue");
    }
    @Bean
    public Queue topicQueue2(){
        return new Queue("topicQueue2");
    }
    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange("BootTopicExchange");
    }
    //创建一个名字为myQueueDirect的队列
    /*@Bean
    public Queue queue(){
        return new Queue("myQueueDirect");
    }*/
    /*@Bean
    public Queue fanoutQueue(){
        return new Queue("fanoutQueue");
    }*/

     /* 将队列绑定到交换机,参数BootRouting为RoutingKey
     * 参数1 为自定义队列对象,参数名queue为自定义队列Bean的id
     * 参数2 为自定义的交换机,参数名myChange为自定义交换机Bean的id
     * */
    /*@Bean("binding")
    public Binding binding(@Qualifier("queue") Queue queue, @Qualifier("myChange")Exchange myChange){
        return BindingBuilder.bind(queue).to(myChange).with("BootRouting").noargs();
    }*/

    //fanout模式绑定
    /*@Bean("binding")
    public Binding binding(@Qualifier("fanoutQueue") Queue queue, @Qualifier("fanoutExchange")FanoutExchange myChange){
        return BindingBuilder.bind(queue).to(myChange);
    }*/

    //topic绑定队列到交换机
    @Bean
    public Binding  topicBinding(Queue topicQueue,TopicExchange topicExchange){
        return BindingBuilder.bind(topicQueue).to(topicExchange).with("Boot.#");
    }
    @Bean
    public Binding  topicBinding2(Queue topicQueue2,TopicExchange topicExchange){
        return BindingBuilder.bind(topicQueue2).to(topicExchange).with("#.text");
    }
}

  发送消息类

@Service
public class TopicSend {
    //自动注入Amqp的模板对象
    @Resource
    private AmqpTemplate template;
    public void topicSend(){
        /*
        * 发送消息
        * 参数1: 交换机名称
        * 参数2: Routingkey
        * 参数3: 为具体的消息内容
         * */
        String message = "凭君莫话封侯事,一将功成万骨枯!";
        template.convertAndSend("BootTopicExchange","Boot.text",message);
        System.out.println("发送消息成功:"+message);
    }
}

  主方法

@SpringBootApplication
public class ApplicationSend {

	public static void main(String[] args) {
		ApplicationContext ac= SpringApplication.run(ApplicationSend.class, args);
		TopicSend send = (TopicSend)ac.getBean("topicSend");
        send.topicSend();
	}

}

三、信息接受端

  接受消息类

@Service
public class TopicReceive {
    //@RabbitListener注解用于标记当前方法为消息监听方法,可以监听某个队列,当队列中有新消息则自动完成接收.
    @RabbitListener(queues ="topicQueue")
    public void receive(String message){
        System.out.println("Boot的topic消息----"+message);
    }

    @RabbitListener(queues ="topicQueue2")
    public void receive2(String message){
        System.out.println("Boot的topic消息2----"+message);
    }
}

  主方法

@SpringBootApplication
public class ApplicationReceive {

	public static void main(String[] args) {
		ApplicationContext ac = SpringApplication.run(ApplicationReceive.class, args);

		TopicReceive receive = (TopicReceive)ac.getBean("topicReceive");
		receive.receive("");
		receive.receive2("");
	}
}
### Spring Boot 集成 RabbitMQ 交换机与队列的工厂初始化实现 在 Spring Boot 中,可以通过声明式的配置类来完成 RabbitMQ 的交换机、队列以及绑定关系的初始化。以下是具体的实现方式: #### 添加依赖 为了支持 RabbitMQ 功能,在项目的 `pom.xml` 文件中需引入以下 Maven 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 此依赖会自动导入 RabbitMQ 所需的核心库和 Spring AMQP 支持[^2]。 #### 创建配置类 通过定义一个 Java 配置类,可以利用 Spring 提供的 Bean 定义机制来初始化交换机、队列及其绑定关系。下面是一个完整的示例代码: ```java import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitMqConfig { // 定义队列 @Bean public Queue myQueue() { return new Queue("my.queue", true, false, false); } // 定义交换机 @Bean public TopicExchange myExchange() { return new TopicExchange("my.exchange"); } // 绑定队列到交换机 @Bean public Binding binding(Queue myQueue, TopicExchange myExchange) { return BindingBuilder.bind(myQueue).to(myExchange).with("routing.key"); } } ``` 在此代码片段中,分别创建了一个持久化的队列 (`my.queue`) 和一个主题类型的交换机 (`my.exchange`) 并将其绑定在一起,指定路由键为 `"routing.key"`[^3]。 #### 工厂模式下的自定义初始化 如果需要更复杂的逻辑控制或者动态参数化,则可通过继承默认的工厂类来自定义行为。例如,重写 `DirectExchange`, `FanoutExchange`, 或者 `TopicExchange` 来满足特定业务场景的要求。 对于高级特性如 **死信队列 (DLQ)** ,也可以通过扩展的方式实现: ```java @Bean public Queue deadLetterQueue() { Map<String, Object> args = new HashMap<>(); args.put("x-dead-letter-exchange", "dlx.exchange"); // 死信转发的目标交换机名称 args.put("x-message-ttl", 60000); // 设置消息存活时间(ms),超时进入 DLX return new Queue("dead.letter.queue", true, false, false, args); } ``` 上述例子展示了如何基于参数化构造函数传递额外属性给队列实例,从而启用死信功能[^3]。 --- #### 性能优化建议 当面对高并发环境时,考虑调整线程池大小或预取计数等性能调优选项可能有助于提升吞吐量和服务稳定性。这些设置通常位于 application.properties/yml 文件下,比如: ```properties spring.rabbitmq.listener.simple.concurrency=5-10 spring.rabbitmq.listener.direct.prefetch=10 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值