Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get topic list from kafka server in Java

I am using kafka 0.8 version and very much new to it.

I want to know the list of topics created in kafka server along with it's metadata. Is there any API available to find out this?

Basically, I need to write a Java consumer that should auto-discover any topic in kafka server.There is API to fetch TopicMetadata, but this needs name of topic as input parameters.I need information for all topics present in server.

like image 271
Anand Avatar asked Jul 23 '14 05:07

Anand


People also ask

How do I check Kafka topics data?

You can use the Kafka-console-consumer to view your messages. It provides a command line utility, bin/kafka-console-consumer.sh, that sends messages from a topic to an output file. To display a maximum number of messages by using: --from-beginning and --max-messages ${NUM_MESSAGES}.

How do you get a list of consumers connected to a Kafka topic?

Get the list of consumer groups for a topic. Use kafka-consumer-groups.sh to list all consumer groups. Note that the below command will list all the consumer groups for all topics managed by the cluster.


2 Answers

with Kafka 0.9.0

you can list the topics in the server with the provided consumer method listTopics();

eg.

Map<String, List<PartitionInfo> > topics;

Properties props = new Properties();
props.put("bootstrap.servers", "1.2.3.4:9092");
props.put("group.id", "test-consumer-group");
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();
consumer.close();
like image 128
betaboy00 Avatar answered Sep 21 '22 16:09

betaboy00


I think this is the best way:

ZkClient zkClient = new ZkClient("zkHost:zkPort");
List<String> topics = JavaConversions.asJavaList(ZkUtils.getAllTopics(zkClient));
like image 23
fengkb Avatar answered Sep 21 '22 16:09

fengkb