[英]How to determine if a kafka topic exists using confluent-kafka-python
I'm using the confluent-kafka-python package to interface with a Kafka server.我正在使用 confluent-kafka-python package 与 Kafka 服务器进行交互。 I can successfully create the topic and push events to it.
我可以成功创建主题并将事件推送到它。 However, my problem lies when I spin up multiple nodes (running in Docker), if a second instance also tries to create the topic I get an error.
但是,我的问题在于当我启动多个节点(在 Docker 中运行)时,如果第二个实例也尝试创建主题,我会收到错误消息。 I need to first check if the topic already exists before creating the new topic.
在创建新主题之前,我需要先检查该主题是否已经存在。
from confluent_kafka.admin import AdminClient, NewTopic
kafka_admin = AdminClient({"bootstrap.servers": server})
# First check here if the topic already exists!
if not topic_exists(topic): # <-- how to accomplish this?
new_kafka_topic = NewTopic(topic, num_partitions=1, replication_factor=1)
results = kafka_admin.create_topics([new_kafka_topic])
Thanks for any help!谢谢你的帮助!
I had the same problem and I managed it in the following way:我遇到了同样的问题,我通过以下方式进行了管理:
client = AdminClient({"bootstrap.servers": BROKER_URL})
topic_metadata = client.list_topics()
if topic_metadata.topics.get(self.topic_name) is None:
self.create_topic()
The AdminClient
class's list_topics
method enables passing the topic name you want to check for, so you do not need to read the full (and potentially large) list of existing topics: AdminClient
类的list_topics
方法允许传递您要检查的主题名称,因此您无需阅读现有主题的完整(可能很大)列表:
list_topics([topic=None][, timeout=-1])
Documentation: https://docs.confluent.io/platform/current/clients/confluent-kafka-python/html/index.html#id0文档: https://docs.confluent.io/platform/current/clients/confluent-kafka-python/html/index.html#id0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.