美文网首页
RabbitMQ使用代码动态绑定

RabbitMQ使用代码动态绑定

作者: 唔哒喂 | 来源:发表于2023-11-07 15:07 被阅读0次

RabbitMQ绑定由代码进行初始化创建
再看某个培训机构的MQ笔记时,了解到,MQ的交换机、队列、绑定关系需要提前声明。
如果手动配置会过于麻烦。

看到他们介绍了这种注入为Bean,再声明的方式,

于是我在消息生产方的配置文件中编写了一段代码,实现了在代码中对于绑定关系的创建。

这是他们介绍使用Configuration代码声明绑定关系的部分代码。

    /**
     * 声明交换机
     * @return Direct类型交换机
     */
    @Bean
    public DirectExchange directExchange(){
        return ExchangeBuilder.directExchange("hmall.direct").build();
    }

    /**
     * 第1个队列
     */
    @Bean
    public Queue directQueue1(){
        return new Queue("direct.queue1");
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingQueue1WithRed(Queue directQueue1, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue1).to(directExchange).with("red");
    }
    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingQueue1WithBlue(Queue directQueue1, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue1).to(directExchange).with("blue");
    }

这是我进行改造了下的代码,主要就是for循环+注入Bean,使得在程序启动时就可以完成绑定,

必要外部依赖:MQ、Hutool、Lombok。【代码中用到的SpringUtil、ReflectUtil均来自于Hutool】

<!--    springBoot-RabbitMQ    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <!-- hu tool -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

自定义实体类

/**
 * @author OutResourceBoy
 * @date 2023/11/3 16:47
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RabbitQueueBindDO {
    private String exchangeName;
    private String exchangeType;
    private String queueName;
    private String routingKey;
}

操作代码

/**
 * 初始化配置 RabbitMQ 交换机 + 队列
 * @author OutResourceBoy
 * @date 2023/11/3 16:35
 */
@Component
@Slf4j
public class InitialRabbitMq{
    @PostConstruct
    public void initial(){
        log.info("[初始化]配置RabbitMQ");
         // 添加绑定1
        RabbitQueueBindDO rabbitQueueBindDO = new RabbitQueueBindDO();
        rabbitQueueBindDO.setExchangeType(ExchangeTypes.TOPIC);
        rabbitQueueBindDO.setExchangeName("aaa.binduser.topic");
        rabbitQueueBindDO.setQueueName("bind.topic.queue");
        rabbitQueueBindDO.setRoutingKey("aaa.topic.user");
        // 添加绑定2【废弃】
       // RabbitQueueBindDO bindDO = new RabbitQueueBindDO();
       // bindDO.setExchangeType(RabbitSendService.WX_EXCHANGE_TYPE);
       // bindDO.setExchangeName(RabbitSendService.WX_LOGIN_EXCHANGE);
       // bindDO.setQueueName(RabbitSendService.WX_LOGIN_QUEUE);
        // bindDO.setRoutingKey(RabbitSendService.WX_QUEUE_ROUTING_KEY);

        ArrayList<RabbitQueueBindDO> rabbitQueueBindDOArrayList = new ArrayList<>();
        rabbitQueueBindDOArrayList.add(rabbitQueueBindDO);
        // rabbitQueueBindDOArrayList.add(bindDO);

        // 注册为Bean
        rabbitQueueBindDOArrayList.forEach(item ->{
            this.inject2Bean(item);
        });
        // 注册到MQ上
        RabbitTemplate rabbitTemplate = SpringUtil.getBean(RabbitTemplate.class);
        rabbitTemplate.convertAndSend("start Running");
        log.info("[初始化]配置RabbitMQ完成");
    }

    private void inject2Bean(RabbitQueueBindDO rabbitQueueBindDO) {
        // 1、声明交换机
        String methodName = rabbitQueueBindDO.getExchangeType() + "Exchange";
        Method declareExchangeMethod = ReflectUtil.getMethodByName(ExchangeBuilder.class, methodName);
        Object o = ReflectUtil.invokeStatic(declareExchangeMethod, rabbitQueueBindDO.getExchangeName());
        String exchangeName = SnowFlakeIdGenerateUtils.getSnowFlakeId();
        ExchangeBuilder ex = (ExchangeBuilder) o;
        Exchange exchange = ex.build();
        SpringUtil.registerBean(exchangeName, exchange);
        // 2、声明队列
        Queue queue = QueueBuilder.durable(rabbitQueueBindDO.getQueueName())
                .lazy()
                .build();
        String queueName = SnowFlakeIdGenerateUtils.getSnowFlakeId();
        SpringUtil.registerBean(queueName, queue);
        // 3、队列交换机绑定
        String bindName = SnowFlakeIdGenerateUtils.getSnowFlakeId();
        Binding binding = BindingBuilder.bind(queue).to(exchange).with(rabbitQueueBindDO.getRoutingKey()).noargs();
        SpringUtil.registerBean(bindName, binding);
    }
}

如果是需要动态配置的,那么我觉得可以使用数据库、nacos等等记录相关配置信息,再把上述代码配置成定时任务。

相关文章

网友评论

      本文标题:RabbitMQ使用代码动态绑定

      本文链接:https://www.haomeiwen.com/subject/qerfwdtx.html