Kafka-python获取主题的分区数

use*_*793 6 python metadata python-2.7 apache-kafka kafka-consumer-api

我正在使用:https://github.com/mumrah/kafka-python作为Python中的kafka api.我想获取指定主题的分区数.我怎么做?

Cha*_*son 8

可能是一个稍微简单的解决方案,但是:

from kafka import KafkaClient

client = KafkaClient('SERVER:PORT')
topic_partition_ids = client.get_partition_ids_for_topic(b'TOPIC')
len(topic_partition_ids)
Run Code Online (Sandbox Code Playgroud)

在Python 3.4.3/kafka-python 0.9.3上测试

  • 这已被弃用,请尝试使用“partitions_for_topic”:https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.partitions_for_topic (3认同)

ste*_*rne 2

我在尝试解决这个完全相同的问题时发现了这个问题。我知道这个问题很老了,但这是我想出的解决方案(使用Kazoo与动物园管理员交谈):

from kazoo.client import KazooClient

class KafkaInfo(object):
    def __init__(self, hosts):
        self.zk = KazooClient(hosts)
        self.zk.start()

    def topics(self):
        return self.zk.get_children('/brokers/topics')

    def partitions(self, topic):
        strs = self.zk.get_children('/brokers/topics/%s/partitions' % topic)
        return map(int, strs)

    def consumers(self):
        return self.zk.get_children('/consumers')

    def topics_for_consumer(self, consumer):
        return self.zk.get_children('/consumers/%s/offsets' % consumer)

    def offset(self, topic, consumer, partition):
        (n, _) = self.zk.get('/consumers/%s/offsets/%s/%d' % (consumer, topic, partition))
        return int(n)
Run Code Online (Sandbox Code Playgroud)