简体   繁体   English

如何使用kafka-python动态创建Kafka中不存在的主题

[英]How to create topics if it does not exists in Kafka dynamically using kafka-python

I'm fairly new to Python and just getting started with Kafka. 我是Python的新手,刚开始使用Kafka。 I am using the library named python-kafka to communicate with Kafka. 我正在使用名为python-kafka的库与Kafka进行通信。 Now I have a requirement that I need to create topics dynamically, however if it does exists, I do not need to create it. 现在,我有一个需要动态创建主题的要求,但是,如果确实存在,则不需要创建它。

From reading the docs I see that I can use KafkaAdminClient to create and delete topics, however I do not find any to check if topic exists. 通过阅读文档,我发现可以使用KafkaAdminClient创建和删除主题,但是我找不到任何可以检查主题是否存在的东西。

The KafkaAdminClient does not expose a method to list topics but you can get the list of existing topics by simply querying the cluster metadata from a KafkaClient . KafkaAdminClient不会公开列出主题的方法,但是您可以通过简单地从KafkaClient查询集群元数据来获取现有主题的列表。

For example, this will print all the topics in the cluster: 例如,这将打印集群中的所有主题:

from kafka.client import KafkaClient

client = KafkaClient(bootstrap_servers='localhost:9092')

future = client.cluster.request_update()
client.poll(future=future)

metadata = client.cluster
print(metadata.topics())

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

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