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
Below shell cmd can print the number of partitions. You should be in kafka bin directory before executing the cmd:
sh kafka-topics.sh --describe --zookeeper localhost:2181 --topic **TopicName** | awk '{print $2}' | uniq -c |awk 'NR==2{print "count of partitions=" $1}'
Note that you have to change the topic name according to your need. You can further validate this using if condition as well:
sh kafka-topics.sh --describe --zookeeper localhost:2181 --topic **TopicName** | awk '{print $2}' | uniq -c |awk 'NR==2{if ($1=="16") print "valid partitions"}'
The above cmd command prints valid partitions if count is 16. You can change count depending on your requirement.