您可以对kafka-topics.sh 使用--list (List all available topics) 选项,查看self.topic 是否存在于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) 以匹配您在代码 sn-p 中的设置。