简体   繁体   English

通过 kafka-python 库检查 python 中是否存在 kafka 主题,不使用消费者和 shell 命令

[英]Check whether kafka topic exists or not in python via kafka-python libraries and without using consumer and shell commands

[This is not a duplicate question because even though similar questions available on stack overflow but no answer is working in my case. [这不是一个重复的问题,因为即使堆栈溢出有类似的问题,但在我的案例中没有答案。 Hence, I am asking my doubt here.]因此,我在这里提出我的疑问。]

I want to fetch list of available Kafka topics and check whether a particular topic exist or not.我想获取可用的 Kafka 主题列表并检查特定主题是否存在。 I wanna do this without using consumer and any shell command.我想在不使用消费者和任何 shell 命令的情况下执行此操作。 I am looking for the solutions via libraries itself.我正在通过图书馆本身寻找解决方案。 So, to fetch list of kafka topic I did following -所以,为了获取我所做的 kafka 主题列表 -

import kafka
client = kafka.KafkaClient(bootstrap_servers='localhost:9092')
topicList = client.topic_partitions

But, here I am getting error as -但是,在这里我收到错误消息 -

'KafkaClient' object has no attribute 'topic_partitions'

It would be a great help if anyone can tell me how to fix the error or suggest me any other solution.如果有人能告诉我如何修复错误或建议我任何其他解决方案,那将是一个很大的帮助。 Thanks in advance.提前致谢。

You can't do this without creating a KafkaConsumer client.如果不创建 KafkaConsumer 客户端,则无法执行此操作。 You get topic partitions in kafka only after they are assigned to a particular consumer.只有在将主题分区分配给特定消费者后,您才能在 kafka 中获得主题分区。

You would have to use the KafkaConsumer client to retrieve the topics.您必须使用KafkaConsumer客户端来检索主题。

Other way to do this is with confluent-kafka consumer client or the admin client, though the latter retuns metadata about the cluster including the topic paritions.其他方法是使用confluent-kafka消费者客户端或管理客户端,尽管后者会重新调整有关集群的元数据,包括主题分区。 With admin client, you can do something like this:使用管理客户端,您可以执行以下操作:

from confluent_kafka.admin import AdminClient
admin_client = AdminClient({'bootstrap.servers': 'localhost:9002'})
admin_client.list_topics().topics

gives

{'topic1': TopicMetadata(topic1, $N partitions),}

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

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