我正在考虑将 Kafka 用作分布式工作队列,多个工作人员可以从中检索任务。我的原始设计如下所示:
Work Producer ---> Kafka topic ------worker 1
|
|__worker 2
...
|__worker n
这个设计的问题是:
如果某个工作人员从主题中获取任务并立即提交偏移量,则在失败的情况下可能不会重新处理该任务。
如果某个工作人员从主题中接手任务并仅在完成时提交偏移量,那么其他工作人员也可能接手该任务并处理它。如果任务持续时间相当长,那么几乎所有工作人员都会接受相同的任务并处理它,从而完全抑制分发性质。
我正在寻找一种方法将队列中的任务“标记”为“进行中”,这样它就不会被其他任何人使用,但不会提交偏移量(因为它可能会失败并需要重新处理)。是否可以实现?
最佳答案
If some worker takes a task from the topic and immediately commits offset then in case of failure the task may not be reprocessed.
在这种情况下,我建议使用手动提交并禁用消费者的 auto.commit.offset 配置。
If some worker takes a task from the topic and commits offset only on finish then other workers may also takes this task and process it. If the task is pretty long lasting then almost all workers will take the same task and process it completely inhibiting the distributing nature.
您可以通过使用分区设计主题和使用 ConsumerGroup 设计消费者来处理这种情况。在 Kafka 中,每个分区只能由 Consumer Group 中的一个消费者线程读取。
这意味着,只要您的所有消费者(或“工作人员”)都属于同一个 ConsumerGroup,就永远不会出现两个工作人员开始阅读和处理同一消息的情况。
关于java - Kafka能否用作分布式工作队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64133706/