SpringBoot集成RabbitMQ-动态注入Bean方式

本文介绍了如何通过遍历枚举的方式动态注入Bean,避免在SpringBoot配置类中显式声明多个RabbitMQ的Queue和Binding Bean。文中详细讲解了Direct、Fanout、Topic和TTL四种使用场景,并提供了关键代码示例,包括配置类、交换机类型枚举、交换机枚举、队列枚举以及消费者的接口定义。
摘要由CSDN通过智能技术生成

实现Direct,Fanout,Topic和死信转发方式实现的延迟队列

一个让处女座程序员很难受的问题: 
每次申明一个队列,都需要用@Bean注解在config类里面显式的往容器里面注入一个Queue Bean和Binding Bean,十几个队列下来,那场面简直不能忍.
怎么解决呢,思路: 
通过遍历枚举的方式,统一往spring容器中注入bean.废话不多说,上代码

一 使用场景说明
1.Direct
根据routekey精确匹配消费,只消费一次
2.Fanout
广播消息队列,同交换机内的所有消费者,都接收到消息
3.Topic
支持模糊匹配,可匹配到多个.配合AnonymousQueue队列可实现集群内多点同一业务集群消费.如:修改集群内所有应用内存中配置
4.TTL
延迟队列,实现消息延迟指定时间消费

二 关键代码

  1. 配置类:
import com.google.common.collect.Maps;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author onlinever
 * @date 2018/09/06
 */
@Service
public class RabbitQueueBeanRegister implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
   

    private ApplicationContext applicationContext;

    private BeanDefinitionRegistry beanDefinitionRegistry;

    private String adapterSuffix = "Adapter";

    private Map<RabbitQueueEnum, Queue> topicQueues = Maps.newHashMap();

    private List<TopicConsumer> topicConsumers;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
   
        this.beanDefinitionRegistry = beanDefinitionRegistry;
        //声明交换机
        declareExchange();
        //声明队列和绑定
        declareQueueAndBinding();
        //奇怪的执行顺序
        if (haveTopicQueue()) {
   
            declareTopicMessageListenerAdapter();
            declareTopicMessageListenerContainer();
        }
    }

    private boolean haveTopicQueue() {
   
        try {
   
            topicConsumers = new ArrayList<>(applicationContext.getBeansOfType(TopicConsumer.class).values());
            return !topicConsumers.isEmpty();
        } catch (Exception e) {
   
            System.out.println(e.getMessage());
            return false;
        }
    }

    /**
     * 声明交换机
     */
    private void declareExchange() {
   
        for (RabbitExchangeEnum rabbitExchangeEnum : RabbitExchangeEnum.
以下是Springboot集成RabbitMq@RabbitListener不自动生成队列的解决方法: 1. 确保已经定义了RabbitAdmin的Bean,并且已经将其注入到了ConnectionFactory中。可以参考如下代码: ```java @Configuration @EnableRabbit public class RabbitConfig { @Bean public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) { RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); // 服务启动时候开启自动启动 rabbitAdmin.setAutoStartup(true); return rabbitAdmin; } @Bean public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); factory.setConcurrentConsumers(3); factory.setMaxConcurrentConsumers(10); factory.setAcknowledgeMode(AcknowledgeMode.MANUAL); return factory; } } ``` 2. 确保在@RabbitListener注解中指定了正确的队列名称。例如: ```java @RabbitListener(queues = "testQueue") public void receiveMessage(String message) { System.out.println("Received message: " + message); } ``` 3. 确保在@RabbitListener注解中指定了正确的Exchange和RoutingKey。例如: ```java @RabbitListener(bindings = @QueueBinding( value = @Queue(value = "testQueue", durable = "true"), exchange = @Exchange(value = "testExchange", type = ExchangeTypes.TOPIC), key = "testRoutingKey" )) public void receiveMessage(String message) { System.out.println("Received message: " + message); } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值