【问题标题】:kafka consumer does not recieve messages in javakafka消费者在java中没有收到消息
【发布时间】:2021-05-01 13:31:16
【问题描述】:

在我的代码中,消费者订阅现有主题但未收到来自主题的消息,请帮助我 它等待消息,而在kafka控制台消费者消息正确接收

package kafka;

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 java.util.Arrays;
import java.util.Properties;

public class SimpleConsumer {
    public static void main(String[] args) throws Exception {

        //Kafka consumer configuration settings
        String topicName = "test12";
        Properties props = new Properties();

        props.put("bootstrap.servers", "localhost:9092");
        props.put("group.id", "test");
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("session.timeout.ms", "30000");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        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);

        //Kafka Consumer subscribes list of topics here.
        consumer.subscribe(Arrays.asList(topicName));

        //print the topic name
        System.out.println("Subscribed to topic " + topicName);
        int i = 0;

        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(1000);
            for (ConsumerRecord<String, String> record : records)

                // print the offset,key and value for the consumer records.
                System.out.printf("offset = %d, key = %s, value = %s\n",
                    record.offset(), record.key(), record.value());
        }
    }
}

【问题讨论】:

  • 尝试使用新的组 id 来查看消费者是否可以阅读消息。如果还是失败了,有没有抛出异常?
  • 检查日志(也包括代理日志)是否有错误。您确定主题名称正确吗?
  • 感谢 @amethystic 的评论。我尝试了新的组 ID,但仍然没有做任何事情,没有任何例外,只是等待......
  • @MatthiasJ.Sax 感谢您的帮助 主题名称正确。
  • 你是在 Mac 上运行吗?听起来像是我正在研究的一个最近的问题(kafka-4348)。见issues.apache.org/jira/browse/KAFKA-4348

标签: java apache-kafka kafka-consumer-api


【解决方案1】:

偏移量可能在最新位置。您可以尝试从头开始搜索。

        HashSet<TopicPartition> partitions = new HashSet<TopicPartition>();
        for (TopicPartition partition : partitions) {
            long offset = consumer.position(partition);
            System.out.println(partition.partition() + ": " + offset);
        }
        consumer.seekToBeginning(partitions);

【讨论】:

  • 感谢@ashwin 这个问题是因为它的升级版本迟到了,但很抱歉
猜你喜欢
  • 2018-09-12
  • 2020-11-15
  • 2022-08-13
  • 2017-11-29
  • 2021-06-06
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多