kafka get partition count for a topic

前端 未结 15 1114
萌比男神i
萌比男神i 2020-12-13 00:05

How can I get number of partitions for any kafka topic from the code. I have researched many links but none seem to work.

Mentioning a few:

http://grokbase.c

15条回答
  •  自闭症患者
    2020-12-13 00:36

    Here's how I do it:

      /**
       * 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 getPartitionsForTopic(String topic, List seedBrokers) {
        for (BrokerInfo seed : seedBrokers) {
          SimpleConsumer consumer = null;
          try {
            consumer = new SimpleConsumer(seed.getHost(), seed.getPort(), 20000, 128 * 1024, "partitionLookup");
            List topics = Collections.singletonList(topic);
            TopicMetadataRequest req = new TopicMetadataRequest(topics);
            kafka.javaapi.TopicMetadataResponse resp = consumer.send(req);
    
            List partitions = new ArrayList<>();
            // find our partition's metadata
            List 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");
      }
    

    Note that I just needed to pull out partition IDs, but you can additionally retrieve any other partition metadata, like leader, isr, replicas, ...
    And BrokerInfo is just a simple POJO that has host and port fields.

提交回复
热议问题