Kafka消费者同步行为

Kafka consumer synchronization behavior

我目前正在探索 kafka 作为一个简单问题的初学者。

There will one Producer pushing message to one Topic but there will be n number of Consumer of spark application massage the data from kafka and insert into database (each consumer inserts to different table).

Is there a possibility that consumers will go out of sync (like some part of the consumer goes down for quite some time), then one or more consumer will not process the message and insert to table ?

assuming the code is always correct, no exception will arise when massaging the data. It is important that every message is processed only once.

我的问题是 Kafka 会为我们处理这部分,还是我们必须编写一些其他代码来确保不会发生这种情况。

您可以对消费者进行分组(请参阅 group.id 配置),并且分组的消费者会在它们之间拆分主题的分区。一旦一个消费者掉线,该组中的另一个消费者将接管被掉线的消费者读取的分区。

但是,可能会存在一些问题:当消费者读取一个分区时,它会将偏移量提交回Kafka,如果消费者在处理接收到的数据之后但在提交偏移量之前丢弃,其他消费者将从最新的可用偏移量开始读取。幸运的是,您可以管理如何提交偏移量的策略(请参阅消费者设置 enable.auto.commitauto.offset.reset 等)

Kafka and Spark Streaming guide 提供一些关于如何管理偏移量的解释和可能的策略。

通过设计,Kafka 将生产者和消费者分离。消费者将尽可能快地阅读 - 并且消费者可以尽可能快地生产。

可以将消费者组织成 "consumer groups",您可以将其设置为多个消费者可以从一个组中读取,也可以将其设置为单个消费者可以从自己的组中读取。

如果你有 1 个消费者到 1 个组,你(取决于你的确认策略)应该能够确保每条消息只被读取一次(每个消费者)。

否则,如果您希望多个消费者从一个组中阅读 - 同样的事情 - 但消息被 n 个消费者中的一个阅读一次。