简体   繁体   English

一旦所有消息被消费,如何关闭kafka消费者?

[英]How to close kafka consumer once all messages are consumed?

I have following program to consume all the messages coming to Kafka. 我有以下程序来消耗所有来到Kafka的消息。

from kafka import KafkaConsumer

consumer = KafkaConsumer('my_test_topic',
                         group_id='my-group',
                         bootstrap_servers=['my_kafka:9092'])
for message in consumer:
    consumer.commit()
    print ("%s key=%s value=%s" % (message.topic,message.key,
                                          message.value))
KafkaConsumer.close()

Using above program i am able to consume all the messages coming to Kafka. 使用上面的程序,我可以使用所有来到Kafka的消息。 But once all messages are consumed, i want to close the kafka consumer which is not happening. 但是一旦所有消息被消费,我想关闭没有发生的kafka消费者。 I need help in same. 我也需要帮助。

I am able to close kafka consumer now if i provide consumer_timeout_ms argument to KafkaConsumer object . 如果我向KafkaConsumer对象提供consumer_timeout_ms参数,我现在能够关闭kafka使用者。 It accepts timeout value in millisecond. 它接受以毫秒为单位的超时值。 Below is the code snippet. 以下是代码段。

from kafka import KafkaConsumer

consumer = KafkaConsumer('my_test_topic',
                         group_id='my-group',
                         bootstrap_servers=['my_kafka:9092'],
                         consumer_timeout_ms=1000)
for message in consumer:
    consumer.commit()
    print ("%s key=%s value=%s" % (message.topic,message.key,
                                          message.value))
KafkaConsumer.close()

In above code if consumer doesn't see any message for 1 second it will close the session. 在上面的代码中,如果消费者在1秒钟内没有看到任何消息,它将关闭会话。

It looks like you want consumer.close() instead of KafkaConsumer.close(). 看起来你想要consumer.close()而不是KafkaConsumer.close()。 It's not documented as a static method. 它没有记录为静态方法。

The Kafka configuration parameter enable.partition.eof is what you need. Kafka配置参数enable.partition.eof就是您所需要的。 When setting this configuration to true. 将此配置设置为true时。 It will emit the PARTITION_EOF event whenever the consumer reaches the end of a partition. 只要消费者到达分区末尾,它就会发出PARTITION_EOF事件。 So you can know when you reach the end of a partition through some callback function. 因此,您可以通过一些回调函数知道何时到达分区的末尾。 By that way, you can choose to close the consumer when you reach the end of all partitions. 通过这种方式,您可以选择在到达所有分区的末尾时关闭使用者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM