[英]Is there a way to get the last message from Kafka topic?
我有一个具有多个分区的Kafka主题,我想知道Java中是否有一种方法可以获取该主题的最后一条消息。 我不在乎我只想获取最新消息的分区。
我尝试了@KafkaListener
但仅在主题更新时才获取消息。 如果打开应用程序后未发布任何内容,则不会返回任何内容。
也许听众根本不是解决问题的正确方法?
您必须使用每个分区中的最新消息,然后在客户端进行比较(如果消息中包含时间戳,则使用消息上的时间戳)。 原因是Kafka不保证分区间排序。 在分区内,可以确保偏移量最大的消息是推送到该消息的最新消息。
以下片段对我有用。 您可以尝试一下。 注释中的解释。
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
consumer.subscribe(Collections.singletonList(topic));
consumer.poll(Duration.ofSeconds(10));
consumer.assignment().forEach(System.out::println);
AtomicLong maxTimestamp = new AtomicLong();
AtomicReference<ConsumerRecord<String, String>> latestRecord = new AtomicReference<>();
// get the last offsets for each partition
consumer.endOffsets(consumer.assignment()).forEach((topicPartition, offset) -> {
System.out.println("offset: "+offset);
// seek to the last offset of each partition
consumer.seek(topicPartition, (offset==0) ? offset:offset - 1);
// poll to get the last record in each partition
consumer.poll(Duration.ofSeconds(10)).forEach(record -> {
// the latest record in the 'topic' is the one with the highest timestamp
if (record.timestamp() > maxTimestamp.get()) {
maxTimestamp.set(record.timestamp());
latestRecord.set(record);
}
});
});
System.out.println(latestRecord.get());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.