卡夫卡消费者手册提交偏移量

时间:2018-11-06 14:27:22

标签: java spring apache-kafka spring-integration spring-integration-dsl

我正在实现dsl spring集成流程,该流程从Kafka获取消息

代码段:

return IntegrationFlows.from(
                Kafka.messageDrivenChannelAdapter(new DefaultKafkaConsumerFactory(kafkaTelemetryDataConsumerConfiguration.getConsumerProperties()),
                        kafkaPropertiesConfiguration.getTelemetryDataTopic()))
                })
                .handle(bla.someImportantOperation())
                //TODO:do manual commit here
                //.handle(consumer.commitSync())

                .get();

我想知道如何.handle(bla.someImportantOperation())成功完成后才能手动commitSync。

由于我使用的是DefaultKafkaConsumerFactory,因此我不知道如何获取消费者参考,希望对您有所帮助。

这些是我用于创建消费者的我的ConsumerProperties:

consumerProperties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaPropertiesConfiguration.getBootstrapServers());
consumerProperties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName());

consumerProperties.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, kafkaPropertiesConfiguration.getClientIdConfig());
consumerProperties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, kafkaPropertiesConfiguration.getGroupIdConfig());

consumerProperties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

1 个答案:

答案 0 :(得分:3)

Kafka.messageDrivenChannelAdapter()为您提供了一个配置器挂钩:

.configureListenerContainer(c ->
                                c.ackMode(ContainerProperties.AckMode.MANUAL))

请注意我提供的选项。

阅读其Javadocs,然后阅读AcknowledgingMessageListener。 这里提到了Acknowledgment。该邮件通过KafkaHeaders.ACKNOWLEDGMENT出现在邮件标题中。

因此,您在//.handle(consumer.commitSync())中所需要的就是这样:

.handle(m -> headers.get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class).acknowledge())

在Spring中查看有关Apache Kafka文档的更多信息:https://docs.spring.io/spring-kafka/docs/2.2.0.RELEASE/reference/html/_reference.html#committing-offsets

相关问题