![](/img/trans.png)
[英]Check whether kafka topic exists or not in python via kafka-python libraries and without using consumer and shell commands
[英]Check whether a Kafka topic exists in Python
如果Kafka主题尚不存在,我想创建它。 我知道如何通过bash创建主题,但我不知道如何检查它是否存在。
topic_exists = ??????
if not topic_exists:
subprocess.call([os.path.join(KAFKABIN, 'kafka-topics.sh'),
'--create',
'--zookeeper', '{}:2181'.format(KAFKAHOST),
'--topic', str(self.topic),
'--partitions', str(self.partitions),
'--replication-factor', str(self.replication_factor)])
另一个不错的方法是使用 python kafka 模块:
kafka_client = kafka.KafkaClient(kafka_server_name)
server_topics = kafka_client.topic_partitions
if topic_name in server_topics:
your code....
kafka_client.topic_partitions 返回主题列表。
您可以使用kafka-topics.sh
的--list (List all available topics)
选项并查看topics
数组中是否存在self.topic
,如下所示。
根据您拥有的主题数量,此方法可能有点繁重。 如果是这种情况,您可能--describe (List details for the given topics)
使用--describe (List details for the given topics)
,如果主题不存在,它可能会返回空。 我还没有对此进行彻底的测试,所以我不能肯定这个解决方案( --describe
)有多可靠,但你可能值得进一步调查。
wanted_topics = ['host_updates_queue', 'foo_bar']
topics = subprocess.check_output([os.path.join(KAFKABIN, 'kafka-topics.sh'),
'--list',
'--zookeeper', '{}:2181'.format(KAFKAHOST)])
for wanted in wanted_topics:
if wanted in topics:
print '\'{}\' topic exists!'.format(wanted)
else:
print '\'{}\' topic does NOT exist!'.format(wanted)
topic_desc = subprocess.check_output([os.path.join(KAFKABIN, 'kafka-topics.sh'),
'--describe',
'--topic', wanted,
'--zookeeper', '{}:2181'.format(KAFKAHOST)])
if not topic_desc:
print 'No description found for the topic \'{}\''.format(wanted)
输出:
root@dev:/opt/kafka/kafka_2.10-0.8.2.1# ./t.py
'host_updates_queue' topic exists!
'foo_bar' topic does NOT exist!
No description found for the topic 'foo_bar'
还有一个Broker Configuration可用,因此您不必执行以下任何步骤:
auto.create.topics.enable | 真实| 在服务器上启用自动创建主题。 如果将其设置为 true,则尝试为不存在的主题生成数据或获取元数据将使用默认复制因子和分区数自动创建它。
如果可能,我会采用这种方法。
请注意,您应该在您的代理上为num.partitions
和default.replication.factor
设置主题配置 ( server.properties
) 以匹配您在代码片段中的设置。
为此使用kafka-python 消费者API。
import kafka
consumer = kafka.KafkaConsumer(group_id='test', bootstrap_servers=your_server_list)
new_topics = set(wanted_topics)-set(consumer.topics())
for topic in new_topics:
create(topic)
使用来自 kafka KafkaAdminClient
的 KafkaAdminClient。未记录但存在方法list_topics
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.