kafka获取主题的分区计数

ztigrdn8  于 2021-06-07  发布在  Kafka
关注(0)|答案(15)|浏览(384)

如何从代码中获取任何kafka主题的分区数。我已经研究了许多链接,但似乎没有工作。
提到几个:
http://grokbase.com/t/kafka/users/148132gdzk/find-topic-partition-count-through-simpleclient-api
http://grokbase.com/t/kafka/users/151cv3htga/get-replication-and-partition-count-of-a-topic
http://qnalist.com/questions/5809219/get-replication-and-partition-count-of-a-topic
类似的讨论。
也有类似的链接,所以没有一个工作的解决方案。

f0ofjuux

f0ofjuux1#

可以从zookeeper shell检索分区数

Syntax: ls /brokers/topics/<topic_name>/partitions

以下是示例:

root@zookeeper-01:/opt/kafka_2.11-2.0.0# bin/zookeeper-shell.sh zookeeper-01:2181
Connecting to zookeeper-01:2181
Welcome to ZooKeeper!
JLine support is disabled

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
ls /brokers/topics/test/partitions
[0, 1, 2, 3, 4]
u4dcyp6a

u4dcyp6a2#

你可以探索 kafka.utils.ZkUtils 其中有许多方法旨在帮助提取有关集群的元数据。这里的答案很好,所以我只是为了多样性补充一下:

import kafka.utils.ZkUtils
import org.I0Itec.zkclient.ZkClient

def getTopicPartitionCount(zookeeperQuorum: String, topic: String): Int = {
  val client = new ZkClient(zookeeperQuorum)
  val partitionCount = ZkUtils.getAllPartitions(client)
    .count(topicPartitionPair => topicPartitionPair.topic == topic)

  client.close
  partitionCount
}
bfrts1fy

bfrts1fy3#

@苏尼尔·帕蒂尔的回答没有回答其中的要点。你得知道名单的大小
producer.partitionsfor(“test”).size()
@vish4071与sunil毫无关联,您在问题中没有提到您正在使用consumerconnector。

x759pob2

x759pob24#

你可以像这样从zookeeper那里得到Kafka分区列表。这是真正的Kafka服务器端分区号。

[zk: zk.kafka:2181(CONNECTED) 43] ls /users/test_account/test_kafka_name/brokers/topics/test_kafka_topic_name/partitions
[35, 36, 159, 33, 34, 158, 157, 39, 156, 37, 155, 38, 154, 152, 153, 150, 151, 43, 42, 41, 40, 202, 203, 204, 205, 200, 201, 22, 23, 169, 24, 25, 26, 166, 206, 165, 27, 207, 168, 208, 28, 29, 167, 209, 161, 3, 2, 162, 1, 163, 0, 164, 7, 30, 6, 32, 5, 160, 31, 4, 9, 8, 211, 212, 210, 215, 216, 213, 19, 214, 17, 179, 219, 18, 178, 177, 15, 217, 218, 16, 176, 13, 14, 11, 12, 21, 170, 20, 171, 174, 175, 172, 173, 220, 221, 222, 223, 224, 225, 226, 227, 188, 228, 187, 229, 189, 180, 10, 181, 182, 183, 184, 185, 186, 116, 117, 79, 114, 78, 77, 115, 112, 113, 110, 111, 118, 119, 82, 83, 80, 81, 86, 87, 84, 85, 67, 125, 66, 126, 69, 127, 128, 68, 121, 122, 123, 124, 129, 70, 71, 120, 72, 73, 74, 75, 76, 134, 135, 132, 133, 59, 138, 58, 57, 139, 136, 56, 137, 55, 64, 65, 62, 63, 60, 131, 130, 61, 49, 143, 48, 144, 145, 146, 45, 147, 44, 148, 47, 149, 46, 51, 52, 53, 54, 140, 142, 141, 50, 109, 108, 107, 106, 105, 104, 103, 99, 102, 101, 100, 98, 97, 96, 95, 94, 93, 92, 91, 90, 88, 89, 195, 194, 197, 196, 191, 190, 193, 192, 198, 199, 230, 239, 232, 231, 234, 233, 236, 235, 238, 237]

您可以在消费代码处使用分区计数。

def getNumPartitions(topic: String): Int = {
    val zk = CuratorFrameworkFactory.newClient(zkHostList, new RetryNTimes(5, 1000))

    zk.start()
    var numPartitions: Int = 0
    val topicPartitionsPath = zkPath + "/brokers/topics/" + topic + "/partitions"

    if (zk.checkExists().forPath(topicPartitionsPath) != null) {
        try {
            val brokerIdList = zk.getChildren().forPath(topicPartitionsPath).asScala
            numPartitions = brokerIdList.length.toInt
        } catch {
            case e: Exception => {
                e.printStackTrace()
            }  
        }  
    }  
    zk.close()

    numPartitions
  }
kupeojn6

kupeojn65#

使用kafkaconsumer的分区列表

//create consumer then loop through topics
    KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
    List<PartitionInfo> partitions = consumer.partitionsFor(topic);

    ArrayList<Integer> partitionList = new ArrayList<>();
    System.out.println(partitions.get(0).partition());

    for(int i = 0; i < partitions.size(); i++){
        partitionList.add(partitions.get(i).partition());
    }

    Collections.sort(partitionList);

应该很有魅力。如果有更简单的方法从主题访问分区列表,请告诉我。

3j86kqsm

3j86kqsm6#

去你的房间 kafka/bin 目录。
然后运行以下命令: ./kafka-topics.sh --describe --zookeeper localhost:2181 --topic topic_name 你应该看看你需要什么 PartitionCount .

Topic:topic_name        PartitionCount:5        ReplicationFactor:1     Configs:
        Topic: topic_name       Partition: 0    Leader: 1001    Replicas: 1001  Isr: 1001
        Topic: topic_name       Partition: 1    Leader: 1001    Replicas: 1001  Isr: 1001
        Topic: topic_name       Partition: 2    Leader: 1001    Replicas: 1001  Isr: 1001
        Topic: topic_name       Partition: 3    Leader: 1001    Replicas: 1001  Isr: 1001
        Topic: topic_name       Partition: 4    Leader: 1001    Replicas: 1001  Isr: 1001
xytpbqjk

xytpbqjk7#

cluster.availablePartitionsForTopic(topicName).size()
0tdrvxhp

0tdrvxhp8#

因此,下面的方法适用于kafka0.10,它不使用任何生产者或消费者api。它使用kafka中scalaapi的一些类,比如zkconnection和zkutils。

ZkConnection zkConnection = new ZkConnection(zkConnect);
    ZkUtils zkUtils = new ZkUtils(zkClient,zkConnection,false);
    System.out.println(JavaConversions.mapAsJavaMap(zkUtils.getPartitionAssignmentForTopics(
         JavaConversions.asScalaBuffer(topicList))).get("bidlogs_kafka10").size());
xxb16uws

xxb16uws9#

//create the kafka producer
def getKafkaProducer: KafkaProducer[String, String] = {
val kafkaProps: Properties = new Properties()
kafkaProps.put("bootstrap.servers", "localhost:9092")
kafkaProps.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer")
kafkaProps.put("value.serializer", 
"org.apache.kafka.common.serialization.StringSerializer")

new KafkaProducer[String, String](kafkaProps)
}
val kafkaProducer = getKafkaProducer
val noOfPartition = kafkaProducer.partitionsFor("TopicName") 
println(noOfPartition) //it will print the number of partiton for the given 
//topic
axkjgtzd

axkjgtzd10#

下面shell cmd可以打印分区数。在执行cmd之前,您应该在kafka bin目录中:

sh kafka-topics.sh --describe --zookeeper localhost:2181 --topic**TopicName**| awk '{print $2}' | uniq -c |awk 'NR==2{print "count of partitions=" $1}'

请注意,必须根据需要更改主题名称。您还可以使用if条件进一步验证此情况:

sh kafka-topics.sh --describe --zookeeper localhost:2181 --topic**TopicName**| awk '{print $2}' | uniq -c |awk 'NR==2{if ($1=="16") print "valid partitions"}'

如果count为16,上面的cmd命令将打印有效分区。您可以根据需要更改计数。

falq053o

falq053o11#

要获得分区列表,理想/实际的方法是使用adminclients api

Properties properties=new Properties();
    properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
    AdminClient adminClient=KafkaAdminClient.create(properties);
    Map<String, TopicDescription> jension = adminClient.describeTopics(Collections.singletonList("jenison")).all().get();
    System.out.println(jension.get("jenison").partitions().size());

它可以作为独立的java方法运行,没有生产者/使用者依赖关系。

brjng4g3

brjng4g312#

我也遇到过同样的问题,我需要为一个主题获取分区。
在答案的帮助下,我从Zookeeper那里得到了信息。
这是我用scala编写的代码(但可以很容易地翻译成java)

import org.apache.zookeeper.ZooKeeper

def extractPartitionNumberForTopic(topicName: String, zookeeperQurom: String): Int = {
  val zk = new ZooKeeper(zookeeperQurom, 10000, null);
  val zkNodeName = s"/brokers/topics/$topicName/partitions"
  val numPartitions = zk.getChildren(zkNodeName, false).size
  zk.close()
  numPartitions
}

使用这种方法,我可以访问有关Kafka主题的信息以及有关Kafka经纪人的其他信息。。。
从zookeeper中,您可以通过浏览来检查主题的分区数 /brokers/topics/MY_TOPIC_NAME/partitions 使用 zookeeper-client.sh 要连接到zookeeper:

[zk: ZkServer:2181(CONNECTED) 5] ls /brokers/topics/MY_TOPIC_NAME/partitions
[0, 1, 2]

这表明这个主题有3个分区 MY_TOPIC_NAME

68de4m5k

68de4m5k13#

我是这样做的:

/**
   * Retrieves list of all partitions IDs of the given {@code topic}.
   * 
   * @param topic
   * @param seedBrokers List of known brokers of a Kafka cluster
   * @return list of partitions or empty list if none found
   */
  public static List<Integer> getPartitionsForTopic(String topic, List<BrokerInfo> seedBrokers) {
    for (BrokerInfo seed : seedBrokers) {
      SimpleConsumer consumer = null;
      try {
        consumer = new SimpleConsumer(seed.getHost(), seed.getPort(), 20000, 128 * 1024, "partitionLookup");
        List<String> topics = Collections.singletonList(topic);
        TopicMetadataRequest req = new TopicMetadataRequest(topics);
        kafka.javaapi.TopicMetadataResponse resp = consumer.send(req);

        List<Integer> partitions = new ArrayList<>();
        // find our partition's metadata
        List<TopicMetadata> metaData = resp.topicsMetadata();
        for (TopicMetadata item : metaData) {
          for (PartitionMetadata part : item.partitionsMetadata()) {
            partitions.add(part.partitionId());
          }
        }
        return partitions;  // leave on first successful broker (every broker has this info)
      } catch (Exception e) {
        // try all available brokers, so just report error and go to next one
        LOG.error("Error communicating with broker [" + seed + "] to find list of partitions for [" + topic + "]. Reason: " + e);
      } finally {
        if (consumer != null)
          consumer.close();
      }
    }
    throw new RuntimeError("Could not get partitions");
  }

请注意,我只需要提取分区ID,但您还可以检索任何其他分区元数据,如 leader , isr , replicas , ...
以及 BrokerInfo 只是一个简单的pojo host 以及 port 领域。

00jrzges

00jrzges14#

在0.82生产者api和0.9消费者api中,您可以使用

Properties configProperties = new Properties();
configProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
configProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.ByteArraySerializer");
configProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

org.apache.kafka.clients.producer.Producer producer = new KafkaProducer(configProperties);
producer.partitionsFor("test")
mtb9vblg

mtb9vblg15#

在java代码中我们可以使用 AdminClient 得到一个主题的和部分。

Properties props = new Properties();
props.put("bootstrap.servers", "host:9092");
AdminClient client = AdminClient.create(props);

DescribeTopicsResult result = client.describeTopics(Arrays.asList("TEST"));
Map<String, KafkaFuture<TopicDescription>>  values = result.values();
KafkaFuture<TopicDescription> topicDescription = values.get("TEST");
int partitions = topicDescription.get().partitions().size();
System.out.println(partitions);

相关问题