简体   繁体   English

如何使用 kafka-python 以编程方式创建主题?

[英]How to programmatically create topics using kafka-python?

I am getting started with Kafka and fairly new to Python.我刚开始使用 Kafka 并且对 Python 相当陌生。 I am using this library named kafka-python to communicate with my Kafka broker.我正在使用这个名为kafka-python库与我的 Kafka 代理进行通信。 Now I need to dynamically create a topic from my code, from the docs what I see is I can call create_topics() method to do so, however I am not sure, how will I get an instance of this class.现在我需要从我的代码动态创建一个主题,从我看到的文档中我可以调用create_topics()方法来这样做,但是我不确定,我将如何获得此类的实例。 I am not able to understand this from the docs.我无法从文档中理解这一点。

Can some one help me with this?有人可以帮我弄这个吗?

You first need to create an instance of KafkaAdminClient .您首先需要创建一个KafkaAdminClient实例。 The following should do the trick for you:以下应该为您解决问题:

from kafka.admin import KafkaAdminClient, NewTopic


admin_client = KafkaAdminClient(
    bootstrap_servers="localhost:9092", 
    client_id='test'
)

topic_list = [NewTopic(name="example_topic", num_partitions=1, replication_factor=1)]
admin_client.create_topics(new_topics=topic_list, validate_only=False)

Alternatively, you can use confluent_kafka client which is a lightweight wrapper around librdkafka :或者,您可以使用confluent_kafka客户端,它是librdkafka的轻量级包装器:

from confluent_kafka.admin import AdminClient, NewTopic


admin_client = AdminClient({"bootstrap_servers": "localhost:9092"})
topic_list = [NewTopic("example_topic", 1, 1)]
admin_client.create_topics(topic_list)

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

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