[英]kafka-python: Can a consumer object join a consumer group without subscribing to any topics?
我有一個topics_subscriber.py
,它不斷檢查任何新主題並訂閱它們。
def _subscribe_topics(consumer: KafkaConsumer) -> None:
topics_to_subscribe = {
topic
for topic in consumer.topics()
if topic.startswith("topic-")
}
subscribed_topics = consumer.subscription()
print(subscribed_topics)
new_topics = (
topics_to_subscribe - subscribed_topics
if subscribed_topics
else topics_to_subscribe
)
if new_topics:
print("new topics detected:")
for topic in new_topics:
print(topic)
print("\nsubscribing to old+new topics\n")
consumer.subscribe(topics=list(topics_to_subscribe)) // subscribe() is not incremental, hence subscribing to old+new topics
print(consumer.subscription())
else:
print("\nno new topics detected: exiting normally\n")
def main() -> None:
consumer = kafka.KafkaConsumer(
client_id="client_1",
group_id="my_group",
bootstrap_servers=['localhost:9092']
)
while True:
_subscribe_topics(consumer)
print("\nsleeping 10 sec\n")
time.sleep(10)
現在,在另一個腳本kafka_extractor.py
中,我想創建一個新的消費者並加入my_group
消費者組,並開始使用該組訂閱的主題中的消息。 即沒有專門為這個新消費者訂閱主題。
def main() -> None:
consumer = kafka.KafkaConsumer(
client_id="client_2",
group_id="my_group",
bootstrap_servers=['localhost:9092']
)
print("created consumer")
print(consumer.subscription())
for msg in consumer:
print(msg.topic)
在 kafka_extractor.py 的kafka_extractor.py
中有兩點需要注意:
print(consumer.subscription())
輸出為 Nonefor msg in consumer:
-> 卡住並且不前進也不退出程序。任何方向將不勝感激。
將消費者加入群組不會獲得群組現有的主題,因為群組可以包含多個主題,消費者實例通過訂閱來決定消費哪些主題
您的循環卡住了,因為它默認從訂閱主題的末尾讀取,但沒有
如果您想使用定期刷新的主題列表,請使用正則表達式訂閱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.