Kafka Consumer does not receive messages

折月煮酒 提交于 2019-12-01 00:20:15

I've encountered the same problem as you. After a long time try, here is the answer.

There are two types of kafka new consumer api that you can choose one.

cousumer.assign(...)

consumer.subscribe(..)

And use like:

    // set these properites or you should run consumer first than run producer
    props.put("enable.auto.commit", "false");
    props.put("auto.offset.reset", "earliest");

    KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);

    boolean assign = false;
    if(assign) {
        TopicPartition tp = new TopicPartition(topic, 0);
        List<TopicPartition> tps = Arrays.asList(tp);
        consumer.assign(tps);
        consumer.seekToBeginning(tps);
    }else {
        consumer.subscribe(Arrays.asList(topic));
    }

http://kafka.apache.org/documentation.html#newconsumerconfigs

If you use old consumer api, it's almost the same about properties config. Remember to add the two following code if you want to see messages produced before consumer consumes:

props.put("enable.auto.commit", "false");
props.put("auto.offset.reset", "earliest");

Hope this will help other people.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!