Kafka 高级消费者使用 Java API 从主题中获取所有消息(相当于 --from-beginning) [英] Kafka High Level Consumer Fetch All Messages From Topic Using Java API (Equivalent to --from-beginning)

查看:36
本文介绍了Kafka 高级消费者使用 Java API 从主题中获取所有消息(相当于 --from-beginning)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自 Kafka 站点的 ConsumerGroupExample 代码测试 Kafka 高级消费者.我想检索关于我在 Kafka 服务器配置中拥有的名为test"的主题的所有现有消息.查看其他博客,auto.offset.reset 应该设置为smallest"才能获取所有消息:

I am testing the Kafka High Level Consumer using the ConsumerGroupExample code from the Kafka site. I would like to retrieve all the existing messages on the topic called "test" that I have in the Kafka server config. Looking at other blogs, auto.offset.reset should be set to "smallest" to be able to get all messages:

private static ConsumerConfig createConsumerConfig(String a_zookeeper, String a_groupId)    {
    Properties props = new Properties();
    props.put("zookeeper.connect", a_zookeeper);
    props.put("group.id", a_groupId);
    props.put("auto.offset.reset", "smallest");
    props.put("zookeeper.session.timeout.ms", "10000");     

    return new ConsumerConfig(props);
}

我真正的问题是:对于高级消费者的等效 Java api 调用是什么,相当于:

The question I really have is this: what is the equivalent Java api call for the High Level Consumer that is the equivalent of:

bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic test --from-beginning

bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic test --from-beginning

推荐答案

基本上,每次新消费者尝试消费一个主题时,它都会从头开始读取消息.如果您每次只是为了测试目的而从头开始消费,那么每次您使用新的 groupID 初始化您的消费者时,它都会从头开始读取消息.我是这样做的:

Basically, everytime a new consumer tries to consume a topic, it'll read messages from the beginning. If you're especially just consuming from the beginning each time for testing purposes, everytime you initialise your consumer with a new groupID, it'll read the messages from the beginning. Here's how I did it :

properties.put("group.id", UUID.randomUUID().toString());

并且每次都从头开始阅读消息!

and read messages from the beginning each time!

这篇关于Kafka 高级消费者使用 Java API 从主题中获取所有消息(相当于 --from-beginning)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆