I am a newbie to Kafka and running a simple kafka consumer/producer example as given on KafkaConsumer and KafkaProducer. When I am running consumer from terminal, consumer is re
Try this one this code worked for me.
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringDeserializer");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringDeserializer");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-consumer-group");
KafkaConsumer myConsumer = new KafkaConsumer<>(props);
myConsumer.subscribe(Arrays.asList(topicName));
myConsumer.subscribe(topics);
try{
while (true) {
ConsumerRecords records = myConsumer.poll(100);
for (ConsumerRecord record : records) {
System.out.println(String.format( "Topic: %s, Partition: %d, Offset: %d, key: %s, value: %s",
record.topic(),record.partition(), record.offset(),record.key(),record.value()
));
}}
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
myConsumer.close();
}