Python kafka:有没有办法在发布新消息之前阻止消费者关注kafka主题?

时间:2018-09-10 17:18:05

标签: python python-3.x apache-kafka kafka-python

我有一个消费者订阅了一个测试主题,生产者线程会定期发布该主题。我希望能够阻塞使用者线程,直到出现新消息为止-然后对其进行处理并开始再次等待。我最接近的是:

consumer = KafkaConsumer(topic_name, auto_offset_reset='latest',
                         bootstrap_servers=[localhost_],
                         api_version=(0, 10), consumer_timeout_ms=1000)
while True:
    print(consumer.poll(timeout_ms=5000))

还有一种惯用的方式吗(或者我看不到这种方式是否存在严重的问题)?

kafka的新手,因此非常欢迎对此设计提出一般建议。完整(运行)示例:

import time
from threading import Thread

import kafka
from kafka import KafkaProducer, KafkaConsumer

print('python-kafka:', kafka.__version__)

def publish_message(producer_instance, topic_name, key, value):
    try:
        key_bytes = bytes(str(key), encoding='utf-8')
        value_bytes = bytes(str(value), encoding='utf-8')
        producer_instance.send(topic_name, key=key_bytes, value=value_bytes)
        producer_instance.flush()
    except Exception as ex:
        print('Exception in publishing message\n', ex)

localhost_ = 'localhost:9092'

def kafka_producer():
    _producer = None
    try:
        _producer = KafkaProducer(bootstrap_servers=[localhost_],
                                  api_version=(0, 10))
    except Exception as ex:
        print('Exception while connecting Kafka')
        print(str(ex))
    j = 0
    while True:
        publish_message(_producer, topic_name, value=j, key=j)
        j += 1
        time.sleep(5)

if __name__ == '__main__':
    print('Running Producer..')
    topic_name = 'test'
    prod_thread = Thread(target=kafka_producer)
    prod_thread.start()
    consumer = KafkaConsumer(topic_name, auto_offset_reset='latest',
                             bootstrap_servers=[localhost_],
                             api_version=(0, 10), consumer_timeout_ms=1000)
    # consumer.subscribe([topic_name])
    while True:
        print(consumer.poll(timeout_ms=5000))

python-kafka: 1.3.5

1 个答案:

答案 0 :(得分:3)

Kafka: The Definitive Guide中也建议进行无限循环轮询。这是Chapter 4. Kafka Consumers: Reading Data from Kafka的Java摘录,使用了相同的想法:

try {
    while (true) {
        ConsumerRecords<String, String> records = consumer.poll(100);
        ...
    }
}

这很好地说明了建议在Python中使用这些库的方式。

kafka-python (请参见A Tale of Two Kafka Clients中的完整示例)

from kafka import KafkaConsumer
...
kafka_consumer = Consumer(
...
)
consumer.subscribe([topic])

running = True
while running:
    message = kafka_consumer.poll()
...

confluent-kafka-python (请参见Introduction to Apache Kafka for Python Programmers中的完整示例)

from confluent_kafka import Consumer, KafkaError
...
c = Consumer(settings)

c.subscribe(['mytopic'])

try:
    while True:
        msg = c.poll(0.1)
...

另一个可能引起密切相关的问题是您如何处理消息。

这部分代码可能依赖于外部依赖项(数据库,远程服务,网络文件系统等),并且可能导致失败的处理尝试。

因此,实施重试逻辑可能是一个好主意,您可以在博客文章Retrying consumer architecture in the Apache Kafka中找到关于它的外观的良好描述。