有没有办法从Kafka主题中获取最后一条消息?

Ban*_*kyo 4 java apache-kafka spring-kafka

我有一个带有多个分区的 Kafka 主题,我想知道 Java 中是否有办法获取该主题的最后一条消息。我不关心我只想获取最新消息的分区。

我已经尝试过,@KafkaListener但它仅在主题更新时才获取消息。如果在应用程序打开后没有发布任何内容,则不会返回任何内容。

也许听众根本就不是解决问题的正确方法?

Jav*_*cal 5

以下代码段对我有用。你可以试试这个。评论中的解释。

        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());
Run Code Online (Sandbox Code Playgroud)