kafka:AdminClient获取指定主题的所有消费者的消费偏移(一)

文章介绍了如何在Kafka中,当有实时性需求时,让消费者从最新的消费偏移开始读取消息,避免处理历史数据。这涉及到获取所有消费者在各个分区的当前消费偏移,通过AdminClientAPI来列表ConsumerGroupOffsets,并计算最大偏移量作为起点。

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实现的。如果在低版本下运行会有兼容性问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10km

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值