简体   繁体   English

如何从 Kafka 主题中获取最近的消息

[英]How to fetch recent messages from Kafka topic

Do we have any option like fetching recent 10/20/ etc., messages from Kafka topic.我们是否有任何选择,例如从 Kafka 主题中获取最近的 10/20/ 等消息。 I can see --from-beginning option to fetch all messages from the topic but if I want to fetch only few messages first, last, middle or latest 10. do we have some options?我可以看到 --from-beginning 选项从主题中获取所有消息,但如果我只想获取少数消息,首先,最后,中间或最新 10. 我们有一些选择吗?

First N messages前 N 条消息

You can use --max-messages N in order to fetch the first N messages of a topic.您可以使用--max-messages N来获取主题的前N消息。

For example, to get the first 10 messages, run例如,要获取前 10 条消息,请运行

bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning  --max-messages 10

Next N messages接下来 N 条消息

bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --max-messages 10

Last N messages最近 N 条消息

To get the last N messages, you need to define a specific partition and the offset:要获取最后 N 条消息,您需要定义一个特定的分区和偏移量:

bin/kafka-simple-consumer-shell.sh --bootstrap-server localhost:9092 --topic test--partition testPartition --offset yourOffset

M to N messages M 到 N 条消息

Again, for this case you'd have to define both the partition and the offset.同样,对于这种情况,您必须同时定义分区和偏移量。 For example, you can run the following in order to get N messages starting from an offset of your choice:例如,您可以运行以下命令以从您选择的偏移量开始获取 N 条消息:

bin/kafka-simple-consumer-shell.sh --bootstrap-server localhost:9092 --topic test--partition testPartition --offset yourOffset --max-messages 10

If you don't want to stick to the binaries, I would suggest you to use kt which is a Kafka command line tool with more options and functionality.如果您不想坚持使用二进制文件,我建议您使用kt ,这是一个具有更多选项和功能的 Kafka 命令行工具。


For more details refer to the article How to fetch specific messages in Apache Kafka有关更多详细信息,请参阅文章如何在 Apache Kafka 中获取特定消息

Without specifying an offset and partition, you'll only be able to consume next N or first N. To consume in the "middle" of the unbounded stream, you need to give the offset如果不指定偏移量和分区,您将只能消耗下一个 N 或第一个 N。要在无界流的“中间”消耗,您需要给出偏移量

Other than console consumer, there's kafkacat除了控制台消费者,还有 kafkacat

First twenty前二十

kafkacat -C -b -t topic -o earliest -c 20

And from previous twenty (from partition zero)从前二十(从分区零)

kafkacat -C -b -t topic -P 0 -o -20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM