Simple Kafka Consumer not receiving messages

后端 未结 6 2264
萌比男神i
萌比男神i 2021-02-09 15:20

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

6条回答
  •  你的背包
    2021-02-09 16:03

    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();
        }
    

提交回复
热议问题