gpt4 book ai didi

java - 卡夫卡消费者。 commitSync 与 commitAsync

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:47 26 4
gpt4 key购买 nike

引自 https://www.safaribooksonline.com/library/view/kafka-the-definitive/9781491936153/ch04.html#callout_kafka_consumers__reading_data_from_kafka_CO2-1

The drawback is that while commitSync() will retry the commit until it either succeeds or encounters a non-retriable failure, commitAsync() will not retry.

这句话我不是很清楚。我想消费者向经纪人发送提交请求,如果经纪人在一段时间内没有响应,则意味着提交失败。我错了吗?

能否详细说明commitSynccommitAsync的区别?
另外,请提供我更喜欢哪种提交类型的用例。

最佳答案

正如 API 文档中所说:


This is a synchronous commits and will block until either the commit succeeds or an unrecoverable error is encountered (in which case it is thrown to the caller).

也就是说,commitSync 是一种阻塞方法。调用它会阻塞您的线程,直到它成功或失败。

例如,

while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value());
consumer.commitSync();
}
}

对于 for 循环中的每次迭代,只有在 consumer.commitSync() 成功返回或因抛出异常而中断后,您的代码才会移至下一次迭代。


This is an asynchronous call and will not block. Any errors encountered are either passed to the callback (if provided) or discarded.

也就是说,commitAsync 是一种非阻塞方法。调用它不会阻塞你的线程。相反,它会继续处理后面的指令,不管最终是成功还是失败。

例如,与前面的例子类似,但是这里我们使用commitAsync:

while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value());
consumer.commitAsync(callback);
}
}

对于 for 循环中的每次迭代,无论 consumer.commitAsync() 最终会发生什么,您的代码都将移至下一次迭代。并且,提交的结果将由您定义的回调函数处理。


权衡:延迟与数据一致性

  • 如果您必须确保数据一致性,请选择commitSync(),因为它会确保在执行任何进一步操作之前,您会知道偏移量提交是成功还是失败。但是因为同步和阻塞,你会花更多的时间等待提交完成,从而导致高延迟。
  • 如果您可以接受某些数据不一致并希望具有低延迟,请选择 commitAsync(),因为它不会等待完成。相反,它只会发出提交请求并稍后处理来自 Kafka 的响应(成功或失败),同时,您的代码将继续执行。

这都是一般来说,实际行为将取决于您的实际代码和调用方法的位置。

关于java - 卡夫卡消费者。 commitSync 与 commitAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46546174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com