检查Python中是否存在卡夫卡主题

检查Python中是否存在卡夫卡主题,python,bash,apache-kafka,Python,Bash,Apache Kafka,如果主题不存在,我想创建一个主题。我知道如何通过bash创建主题,但不知道如何检查它是否存在 topic_exists = ?????? if not topic_exists: subprocess.call([os.path.join(KAFKABIN, 'kafka-topics.sh'), '--create', '--zookeeper', '{}:2181'.format(KAFKAHOST), '--topic', str

如果主题不存在,我想创建一个主题。我知道如何通过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)])
您可以对
kafka topics.sh
使用
--list(列出所有可用主题)
选项,并查看
topics
数组中是否存在
self.topic
,如下所示

根据主题的数量,这种方法可能有点繁重。如果是这种情况,您可能可以使用
--description(列出给定主题的详细信息)
,如果主题不存在,它可能会返回空。我还没有完全测试过这个,所以我不能肯定这个解决方案(
--descripe
)有多可靠,但可能值得您进一步研究

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'
还有一个可用的解决方案,因此您无需执行以下任何步骤:

auto.create.topics.enable | true |在服务器上启用自动创建主题。如果设置为true,则尝试为不存在的主题生成数据或获取元数据时,将使用默认复制因子和分区数自动创建该主题

如果可能的话,我会采取这种方法


请注意,您应该在代理上为
num.partitions
default.replication.factor
设置主题配置(
server.properties
),以匹配代码段中的设置。

另一个好方法是使用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_分区返回主题列表

为此使用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)

是的,一个直截了当的解决方案。谢谢。@ThS不小心引用了错误的代理配置。我将帖子改为quote
auto.create.topics.enable
,这是完成此任务的正确配置。请注意,默认值为
true
,因此您可能无需执行任何操作:)一直在寻找一种方法来执行此操作。从文件上看不明显,我想。@sshow请在这里写下你在寻找什么,这样下一个有你问题的人会更快地发现:)这正是我在寻找的。如果这个主题不存在,我需要一种提前失败的方法,因为目前(kafka python 1.3.5)当使用者开始轮询不存在的主题时,由于无限循环,使用者会消耗100%的CPU。我还需要主题列表,因此我尝试了此代码,但出现错误-“KafkaClient”对象没有属性“topic\u partitions”,有人能帮我解释为什么会这样吗