使用分区获取kafka 0.8.0中生产者的分区数量对于方法
问题描述:
我们是否支持kafka 0.8.0版本中的生产者的partitionsFor
方法?我想用这种方法来获得给定kafka主题的分区数量。使用分区获取kafka 0.8.0中生产者的分区数量对于方法
如果此方法在kafka 0.8.0中不可用,那么在此特定版本的kafka中获取生产者中分区数的最简单方法是什么?
答
您可以使用listTopics()方法也
ArrayList<Topics> topicList = new ArrayList<Topics>();
Properties props = new Properties();
Map<String, List<PartitionInfo>> topics;
Topics topic;
InputStream input =
getClass().getClassLoader().getResourceAsStream("kafkaCluster.properties");
try {
props.load(input);
props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
props.getProperty("BOOTSTRAP_SERVERS_CONFIG"));
props.put("key.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String,
String>(props);
topics = consumer.listTopics();
// System.out.println(topics.get(topics));
for (Map.Entry<String, List<PartitionInfo>> entry :
topics.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " +
entry.getValue());
topic = new Topics();
topic.setTopic_name(entry.getKey());
topic.setPartitions(Integer.toString(entry.getValue().size()));
topicList.add(topic);
}
} catch (IOException e) {
e.printStackTrace();
}
答
你为什么不试试以下方法 https://stackoverflow.com/a/35458605/5922904。 另外ZkUtils有getPartitionsForTopics方法也可以使用。虽然我还没有尝试过,并测试它自己
在这里,在数组元素的数量是分区的数量。 – Megha