Kafka消费者上线时默认都是从上次消费的偏移开始读取消息
在对消息系统的应用场景中,当有实时性要求时,希望忽略掉上线之前的所有消息,只从所有消费者最后的消费偏移读取消息。
就好比加入微信群时,不会收进群之前的消息。
那么我们接收消息之前就需要知道其他消费者的当前消费偏移,计算出最大值,从最大的偏移开始读取消息。
以下示例基于AdminClient获取指定消费主题的所有消费者的消费偏移。
/**
* 获取指定主题的消费偏移
*/
@Test
public void testConsumerOffset() {
// 配置Kafka消费者的属性
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
// 消费主题
String topic="datatopic";
// Create AdminClient
try (AdminClient adminClient = AdminClient.create(props)) {
// 获取消费者列表
Collection<ConsumerGroupListing> consumerGroupListing = adminClient.listConsumerGroups().all().get();
for (ConsumerGroupListing consumerGroup : consumerGroupListing) {
String groupId = consumerGroup.groupId();
// 获取消费者在每个分区的消费偏移
ListConsumerGroupOffsetsResult offsetsResult = adminClient.listConsumerGroupOffsets(groupId);
Map<TopicPartition, OffsetAndMetadata> offsets = offsetsResult.partitionsToOffsetAndMetadata().get();
// 输出指定主题的消费偏移
for (Map.Entry<TopicPartition, OffsetAndMetadata> entry : offsets.entrySet()) {
TopicPartition topicPartition = entry.getKey();
if(topic.equals(topicPartition.topic())) {
OffsetAndMetadata offsetAndMetadata = entry.getValue();
long offset = offsetAndMetadata.offset();
System.out.println("Consumer group: " + groupId + ", Topic: " + topicPartition.topic() +
", Partition: " + topicPartition.partition() + ", Offset: " + offset);
}
}
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
注意:本示例是基于kafka client 最新版本kafka-clients-3.5.0.jar实现的。如果在低版本下运行会有兼容性问题