我在Python中使用:https://github.com/mumrah/kafka-python作为kafka api。我想要获取指定主题的分区数量。我该怎么做?
发布于 2015-05-18 22:07:53
这可能是一个稍微简单的解决方案,但是:
from kafka import KafkaClient
client = KafkaClient('SERVER:PORT')
topic_partition_ids = client.get_partition_ids_for_topic(b'TOPIC')
len(topic_partition_ids)在Python 3.4.3 / kafka-python 0.9.3上测试
发布于 2015-05-07 14:34:11
我在尝试解决这个完全相同的问题时发现了这个问题。我知道这个问题很老,但这是我想出的解决方案(使用Kazoo与zookeeper对话):
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)发布于 2021-08-04 07:03:54
Python 3.8.10/kafka-python 2.0.2解决方案:
from kafka import KafkaConsumer
def get_partitions_number(server, topic):
consumer = KafkaConsumer(
topic,
bootstrap_servers=server
)
partitions = consumer.partitions_for_topic(topic)
return len(partitions)https://stackoverflow.com/questions/29612228
复制相似问题