Spring-Kafka —— 实现批量消费和手动提交offset - 曹伟雄

时间:2024-03-06 22:01:54

Spring-Kafka —— 实现批量消费和手动提交offset

 

spring-kafka的官方文档介绍,可以知道自1.1版本之后,

@KafkaListener开始支持批量消费,只需要设置batchListener参数为true

把application.yml中的enable-auto-commit设置为false,设置为不自动提交

 

@Bean
public KafkaListenerContainerFactory<?> batchFactory(ConsumerFactory consumerFactory){
    ConcurrentKafkaListenerContainerFactory<Integer,String> factory =
    new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(consumerFactory);
    factory.setConcurrency(10);
    factory.getContainerProperties().setPollTimeout(1500);
    factory.setBatchListener(true);//设置为批量消费,每个批次数量在Kafka配置参数中设置
    factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);//设置手动提交ackMode
  return factory; 
}
   //批量消息
    @KafkaListener(topics = {"first_top"},containerFactory="batchFactory")
    public void consumerBatch(List<ConsumerRecord<?, ?>> records, Acknowledgment ack){
        log.info("接收到消息数量:{}",record.size());
       //手动提交
      ack.acknowledge();
}

这里containerFactory = “batchFactory”要指定为批量消费