Springboot运行时动态创建队列消费者

2021-07-13  本文已影响0人  TinyThing

0x0 背景

在有些项目中,我们只有在项目启动后才知道需要监听哪些消息,这种情况下无法通过springboot配置文件来生成消息Listener;
因此需要我们手动在运行时创建消息监听器。本文写了一个简单的demo以及开发注意事项,供大家参考。

0x1 原理

核心类是AmqpAdmin以及其实现类RabbitAdmin,这个类包含了注册queue、exchange以及binding的方法:

    /**
     * Declare the given queue.
     * @param queue the queue to declare.
     * @return the name of the queue.
     */
    @Nullable
    String declareQueue(Queue queue);

    /**
     * Declare an exchange.
     * @param exchange the exchange to declare.
     */
    void declareExchange(Exchange exchange);


    /**
     * Declare a binding of a queue to an exchange.
     * @param binding a description of the binding to declare.
     */
    void declareBinding(Binding binding);

我们只需要注入该类到相应的Service中,即可利用这几个方法实现运行时动态注册queue,动态绑定queue和exchange;

这里要注意一个问题:注入bean的时候要用AmqpAdmin,不能用RabbitAdmin,否则注不进去。因为rabbitMq自动配置生成的地方用的是AmqpAdmin:

        public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
            return new RabbitAdmin(connectionFactory);
        }

0x2 完整代码

完整代码如下:

@Service
@Slf4j
@RequiredArgsConstructor
public class MqFactory {

    private final SimpleRabbitListenerContainerFactory containerFactory;

    private final AmqpAdmin rabbitAdmin;

    private final List<MessageListenerContainer> messageListenerContainerList = new ArrayList<>();

    public void createMessageListener(String tableName) {
        log.info("- create message listener for model: {}", tableName);

        //生成队列、交换机和绑定规则,绑定key为 = data.sync.key.表名称
        Queue queue = new Queue("");
        TopicExchange exchange = new TopicExchange(EXCHANGE);
        Binding binding = BindingBuilder.bind(queue).to(exchange).with(KEY_PREFIX + tableName);
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(binding);

        SimpleMessageListenerContainer container = containerFactory.createListenerContainer();
        container.setQueues(queue);
        container.setMessageListener(message -> handleMessage(tableName, message));
        container.start();

        messageListenerContainerList.add(container);
        log.info("- create message listener finish");
    }

    private void handleMessage(String tableName, Message message) {

        byte[] body = message.getBody();
        String json = new String(body);

        log.info("- handle table: {} message: {}", tableName, json);
    }


    @PreDestroy
    public void destroy() {
        messageListenerContainerList.forEach(Lifecycle::stop);
        log.info("- stop all message listeners...");
    }

}

上一篇 下一篇

猜你喜欢

热点阅读