mq 消费者数量是监听器监听的,我们就可以在不重启项目时,调整消费者数量。

通过web动态设置消费者数量

@Resource
RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry;
 
@RequestMapping(value = "/modifyMqConsumerNum")
@ApiOperation(value = "更新队列消费者数量接口")
public Response modifyMqConsumerNum(@RequestParam(value = "queueName", required = false) String queueName,
                                    @RequestParam(value = "concurrentConsumers") Integer concurrentConsumers,
                                    @RequestParam(value = "maxConcurrentConsumers") Integer maxConcurrentConsumers) {
    Collection<MessageListenerContainer> listenerContainers = rabbitListenerEndpointRegistry.getListenerContainers();
    for (MessageListenerContainer container : listenerContainers) {
        SimpleMessageListenerContainer con = (SimpleMessageListenerContainer) container;
        //消息监听容器要消费的队列名称集合
        List<String> queueNamesList = Arrays.asList(con.getQueueNames());
        //判断容器中的队列名称是否包含需要调整的队列名参数
        if (queueNamesList.contains(queueName)) {
            //注意先设置最大的消费者数量,再设置最小的消费者数量,因为先修改最小数量超过修改前的最大数量时会报异常修改失败
            con.setMaxConcurrentConsumers(maxConcurrentConsumers);
            con.setConcurrentConsumers(concurrentConsumers);
        }
    }
    return Response.success();
}