Apache kafka consumer in java simple example

/
0 Comments
Here is a simple java program for apache kafka consumer. This java program is ready to use in your code base or project.
 import java.util.Collections; 
import java.util.Properties; 
 import org.apache.kafka.clients.consumer.ConsumerConfig; 
import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.ConsumerRecords;
 import org.apache.kafka.clients.consumer.KafkaConsumer;
 public class KafkaConsumerExample {

 public static void main(String[] args) {

 Properties props = new Properties();
 props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "myGroupId"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

 KafkaConsumer consumer = new KafkaConsumer<>(props);
 consumer.subscribe(Collections.singletonList("myTopic")); 

 while (true) {
 ConsumerRecords records = consumer.poll(100); 
 for (ConsumerRecord record : 

records) { 

 System.out.println(record.value()); 
 } 
 } 
 } 
}

This example assumes that Kafka is running on the local machine at port 9092, 
 continuously poll for new messages on the topic and print the value of each message it receives.

Note that for production use, you should consider adding error
 handling and offset committing logic to the consumer code.


You may also like

No comments: