在網上碰到的問題,想了下使用現有的API仍是能夠實現的。java
首先,須要引入Kafka服務器端代碼,好比加入Kafka 1.0.0依賴:apache
Maven服務器
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.12</artifactId>
<version>1.0.0</version>
</dependency>spa
Gradlescala
compile group: 'org.apache.kafka', name: 'kafka_2.12', version: '1.0.0'blog
而後編寫獲取訂閱某topic的全部group的方法,代碼以下:get
/** * get all subscribing consumer group names for a given topic * @param brokerListUrl localhost:9092 for instance * @param topic topic name * @return */ public static Set<String> getAllGroupsForTopic(String brokerListUrl, String topic) { AdminClient client = AdminClient.createSimplePlaintext(brokerListUrl); try { List<GroupOverview> allGroups = scala.collection.JavaConversions.seqAsJavaList(client.listAllGroupsFlattened().toSeq()); Set<String> groups = new HashSet<>(); for (GroupOverview overview: allGroups) { String groupID = overview.groupId(); Map<TopicPartition, Object> offsets = scala.collection.JavaConversions.mapAsJavaMap(client.listGroupOffsets(groupID)); Set<TopicPartition> partitions = offsets.keySet(); for (TopicPartition tp: partitions) { if (tp.topic().equals(topic)) { groups.add(groupID); } } } return groups; } finally { client.close(); } }