繁体   English   中英

Apache Kafka 获取特定主题的消费者列表

[英]Apache Kafka get list of consumers on a specific topic

由于它可以是标题中的客人,有没有办法在java中获取特定主题的消费者列表? 直到现在我才能得到这样的主题列表

    final ListTopicsResult listTopicsResult = adminClient.listTopics();
    KafkaFuture<Set<String>> kafkaFuture = listTopicsResult.names();
    Set<String> map = kafkaFuture.get();

但我还没有找到一种方法来获取每个主题的消费者列表

我最近正在为我的 kafka 客户端工具解决同样的问题。 这并不容易,但我从代码中发现的唯一方法如下:

Properties props = ...//here you put your properties
AdminClient kafkaClient = AdminClient.create(props);

//Here you get all the consumer groups
List<String> groupIds = kafkaClient.listConsumerGroups().all().get().
                       stream().map(s -> s.groupId()).collect(Collectors.toList()); 

//Here you get all the descriptions for the groups
Map<String, ConsumerGroupDescription> groups = kafkaClient.
                                               describeConsumerGroups(groupIds).all().get();
for (final String groupId : groupIds) {
    ConsumerGroupDescription descr = groups.get(groupId);
    //find if any description is connected to the topic with topicName
    Optional<TopicPartition> tp = descr.members().stream().
                                  map(s -> s.assignment().topicPartitions()).
                                  flatMap(coll -> coll.stream()).
                                  filter(s -> s.topic().equals(topicName)).findAny();
            if (tp.isPresent()) {
                //you found the consumer, so collect the group id somewhere
            }
} 

这个 API 从 2.0 版本开始可用。 可能有更好的方法,但我找不到。 您还可以在我的bitbucket上找到代码

消费者不受某个主题的束缚。 他们与消费者群体联系在一起

获取一个topic的所有consumer,首先要列出所有的groups,然后在每个group内筛选出你的topic

它将以AdminClient.listConsumerGroups开头,然后是AdminClient.describeConsumerGroups

这将为您提供包含“成员”的描述列表,您可以在其中找到主题

https://kafka.apache.org/20/javadoc/org/apache/kafka/clients/admin/ConsumerGroupDescription.html

注意:有一些外部工具可以让这更容易,比如 Hortonworks SMM https://docs.hortonworks.com/HDPDocuments/SMM/SMM-1.2.0/monitoring-kafka-clusters/content/smm-monitoring-consumers.html

我知道这个主题有点陈旧,但我目前正在开发一个仪表板,它需要列出具有相关消费者群体的主题。 Katya 的回答是可以的,但它仍然不会为没有活跃成员的消费者组列出 TopicPartitions。 我遇到了这个解决方案,希望它有所帮助:

Properties props = ...//here you put your properties
AdminClient kafkaClient = AdminClient.create(props);

Map<TopicPartition, OffsetAndMetadata> offsets = kafkaClient
    .listConsumerGroupOffsets("consumer_group_name")
    .partitionsToOffsetAndMetadata()
    .get();

可以针对特定主题解析偏移映射中的 TopicPartition。 可以针对Katya 的回答中的整个 groupId 列表重复此列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM