@RabbitListener 批量处理

当接收 一批消息时,通常由容器执行解批处理,监听器一次接收一条消息。 从 2.2 版本开始,您可以配置监听器容器工厂和监听器,以便在一次调用中接收整个批次,只需设置工厂的 batchListener 属性,并将方法负载参数设为 ListCollection

@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory());
    factory.setBatchListener(true);
    return factory;
}

@RabbitListener(queues = "batch.1")
public void listen1(List<Thing> in) {
    ...
}

// or

@RabbitListener(queues = "batch.2")
public void listen2(List<Message<Thing>> in) {
    ...
}

batchListener 属性设置为 true 会自动关闭工厂创建的容器中的 deBatchingEnabled 容器属性(除非 consumerBatchEnabledtrue - 参见下文)。实际上,解批处理从容器移至监听器适配器,适配器创建传递给监听器的列表。

启用批处理的工厂不能与 多方法监听器一起使用。

同样从 2.2 版本开始,当一次接收一批消息时,最后一条消息包含一个设置为 true 的布尔头。 可以通过在监听器方法中添加 @Header(AmqpHeaders.LAST_IN_BATCH) boolean last` 参数来获取此头。 该头是从 MessageProperties.isLastInBatch() 映射的。 此外,AmqpHeaders.BATCH_SIZE 会在每个消息片段中填充批次的大小。

此外,SimpleMessageListenerContainer 中添加了一个新属性 consumerBatchEnabled。 当它为 true 时,容器将创建一批消息,最多达到 batchSize;如果在 receiveTimeout 过去后没有新消息到达,则会传递部分批次。 如果接收到生产者创建的批次,它将被解批并添加到消费者端批次;因此,实际传递的消息数量可能超过 batchSizebatchSize 表示从代理接收到的消息数量。 当 consumerBatchEnabled 为 true 时,deBatchingEnabled 必须为 true;容器工厂将强制执行此要求。

@Bean
public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory() {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(rabbitConnectionFactory());
    factory.setConsumerTagStrategy(consumerTagStrategy());
    factory.setBatchListener(true); // configures a BatchMessageListenerAdapter
    factory.setBatchSize(2);
    factory.setConsumerBatchEnabled(true);
    return factory;
}

consumerBatchEnabled@RabbitListener 一起使用时:

@RabbitListener(queues = "batch.1", containerFactory = "consumerBatchContainerFactory")
public void consumerBatch1(List<Message> amqpMessages) {
    ...
}

@RabbitListener(queues = "batch.2", containerFactory = "consumerBatchContainerFactory")
public void consumerBatch2(List<org.springframework.messaging.Message<Invoice>> messages) {
    ...
}

@RabbitListener(queues = "batch.3", containerFactory = "consumerBatchContainerFactory")
public void consumerBatch3(List<Invoice> strings) {
    ...
}
  • 第一个使用接收到的原始、未转换的 org.springframework.amqp.core.Message 调用。

  • 第二个使用带有已转换负载和已映射头/属性的 org.springframework.messaging.Message<?> 调用。

  • 第三个使用已转换的负载调用,无法访问头/属性。

您还可以添加 Channel 参数,这在使用 MANUAL 确认模式时经常使用。 这对于第三个示例不是很有用,因为您无法访问 delivery_tag 属性。

Spring Boot 为 consumerBatchEnabledbatchSize 提供了配置属性,但没有为 batchListener 提供。 从 3.0 版本开始,在容器工厂上将 consumerBatchEnabled 设置为 true 也会将 batchListener 设置为 true。 当 consumerBatchEnabledtrue 时,监听器*必须*是批处理监听器。

从 3.0 版本开始,监听器方法可以消费 Collection<?>List<?>

批量模式下的监听器不支持回复,因为批次中的消息和产生的单个回复之间可能没有关联。 异步返回类型仍然支持批处理监听器。