Created
February 7, 2022 19:53
-
-
Save jwkidd3/8ab1f7f2142a103d210ba0d82b428aee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kiddcorp; | |
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; | |
import org.apache.kafka.common.serialization.StringDeserializer; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import java.time.Duration; | |
import java.util.Collections; | |
import java.util.Properties; | |
/** | |
* Example of a simple consumer | |
*/ | |
public class ConsumerDemo { | |
public static void main(String[] args) { | |
Logger logger = LoggerFactory.getLogger(ConsumerDemo.class); | |
String bootstrapServers = "localhost:9092,localhost:9091"; | |
String topic = "testTopic"; | |
String groupId = "G1"; | |
Properties properties = new Properties(); | |
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); | |
properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); | |
properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); | |
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, groupId); | |
//create consumer | |
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties); | |
//subscribe to our topic(s) | |
consumer.subscribe(Collections.singletonList(topic)); | |
//poll for new data | |
while (true) { | |
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); | |
for (ConsumerRecord<String, String> record : records) { | |
System.out.printf("\nKey: %s\nValue: %s\nPartition: %s\nOffset: %s\n", | |
record.key(), record.value(), record.partition(), record.offset()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment