无法使用 python-kafka 消费消息

Unable to consume messages using python-kafka

我试图复制 blog 中给出的步骤。在尝试时,给出了 Kafka ConsumerKafka Producer python 代码,我能够 运行 python 交互式终端中的代码,并且消费者控制台能够提供输出,但是如果我在 python 文件 (*.py) 中传递它们,它不会消耗任何东西。

消费者

from kafka import KafkaConsumer
consumer = KafkaConsumer('sample')
for message in consumer:
    print (message)

制作人

from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers='localhost:9092')
producer.send('sample', b'Hello, World!')
producer.send('sample', key=b'message-two', value=b'This is Kafka-Python')

如何让它在 python 文件中工作?

I just added producer.flush() to the producer code, and it started to work.

因为 Kafka 客户端批量发送消息,而不是立即发送以减少代理的负载。

您最初没有发送足够的数据来自行进行刷新,因此您的数据只是在应用程序结束时留在内存中。

参考batch.size制作人属性