简体   繁体   English

如何只获取Kafka主题的最新消息?

[英]How to get only the latest message of a Kafka topic?

Is there a way to decompose the messages so that only the latest message is consumed? 有没有办法分解消息,以便只消耗最新的消息?

I tried to save the messages in a list, but it didn't really work out 我试图将消息保存在列表中,但它并没有真正解决

var consumer = new Consumer(new ConsumerOptions(topic, router));

foreach (var message in consumer.Consume())
{
    Console.WriteLine(Encoding.UTF8.GetString(message.Value));
}

Output should be: 1, 2, 3, 4 输出应为: 1,2,3,4

Output is: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4 输出为: 1,1,2,1,2,3,1,2,3,4

As a matter of fact, the only way to do what you want is to have a topic with single partition and setting max.poll.records to one. 事实上,做你想做的事情的唯一方法是让一个主题具有单个分区并将max.poll.records设置为一个。

Otherwise, there is no way to to it, because the last message does not make sense. 否则,没有办法,因为最后一条消息没有意义。 Any input message can be pushed into different partitions and you have some last messages relative to the number of partitions your topic has. 任何输入消息都可以推送到不同的分区,并且您有一些与主题所具有的分区数相关的最后消息。

You can use something called Log Compaction which will "truncate" messages with the same key. 您可以使用名为Log Compaction的内容 ,它将使用相同的密钥“截断”消息。 So when you send messages with the same key you will get only the last message/value for that key. 因此,当您使用相同的密钥发送邮件时,您将只获得该密钥的最后一条消息/值。 This feature is enabled by default. 默认情况下启用此功能。 When you send the messages 1, 1, 2, 1, 2, 3, 1, 2, 3, 4 and you want to read them as 1, 2, 3, 4 you give the messages the same keys, which should be overwritten by each other (so all the 1 messages get the same key, all the 2 messages get the same key, ...). 当你发送消息1,1,2,1,2,3,1,2,3,4并想要将它们读为1,2,3,4时,你给消息提供相同的密钥,这些密钥应该被覆盖彼此相关(因此所有1条消息都获得相同的密钥,所有2条消息都获得相同的密钥,...)。

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

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