我有一个具有多个分区的Kafka主题,我想知道在Java中是否有一种方法可以获取该主题的最新消息。 我不关心分区,只想获取最新的消息。
我尝试过使用
也许监听器根本不是解决问题的正确方法?
我尝试过使用
@KafkaListener
,但仅在更新主题时才会获取消息。如果在打开应用程序后没有发布任何内容,则不返回任何信息。也许监听器根本不是解决问题的正确方法?
@KafkaListener
,但仅在更新主题时才会获取消息。如果在打开应用程序后没有发布任何内容,则不返回任何信息。 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());