kafka~消息的批量拉取

kafka支持一次拉取批量的消息,max.poll.records这个配置用来设置一次拉取的消息数量,可以自己定义KafkaListenerContainerFactory来开启消费者批量监听消息的功能.

KafkaBlukConfig配置

@Configuration
public class KafkaBlukConfig {
    @Value("${spring.kafka.hosts}")
    private String bootstrapServers;
    @Value("${spring.kafka.consumer.max-poll-records:30}")
    private Integer maxPollRecords;
    @Value("${spring.kafka.consumer.groupId:group1}")
    private String group;

    /**
     * 消费者配置信息
     */
    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, group);
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 120000);
        props.put(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, 180000);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return props;
    }

    /**
     * 消费者批量⼯程
     */
    @Bean
    public KafkaListenerContainerFactory<?> batchFactory() {
        ConcurrentKafkaListenerContainerFactory<Integer, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(consumerConfigs()));
        //设置为批量消费,每个批次数量在Kafka配置参数中设置ConsumerConfig.MAX_POLL_RECORDS_CONFIG
        factory.setBatchListener(true);
        return factory;
    }
}

消费者指定factory

    @KafkaListener(id = "consumer1", topics = "${nezha.listener.topicName}", containerFactory = "batchFactory")
    public void listenYaosu(List<ConsumerRecord<String, String>> record) throws Exception {
        doBulkEvent(record);
    }
  • 通过consumer1这个名称,可以控制消费者的启动和停止
@RestController
public class ApiController {
    public static String listenerId = "Consumer1";
    @Autowired
    private KafkaListenerEndpointRegistry kafkaRegistry;

    @GetMapping("kafka-restart")
    public ResponseEntity start() {
        kafkaRegistry.getListenerContainer(listenerId).start();
        return ResponseEntity.ok("操作成功");
    }

    @GetMapping("kafka-stop")
    public ResponseEntity stop() {
        kafkaRegistry.getListenerContainer(listenerId).stop();
        return ResponseEntity.ok("操作成功");
    }
}

posted @ 2022-06-24 15:11  张占岭  阅读(528)  评论(0编辑  收藏  举报