[英]How to get consumer-id using a @KafkaListener spring boot 2 consumer
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-consumer
是否有可能在Spring boot @KafkaListener consumer
中獲取像上面的命令 output 中的consumer-id
信息?
我想將此消費者 ID 添加到表中以表示處理數據的處理器。
我已經閱讀了@gary-russell 關於如何獲取 kafka consumer-id for logging的回答,但我沒有看到 consumer-id 出現在分區分配的日志中。
[org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO o.s.k.l.KafkaMessageListenerContainer.info - my-consumer: partitions assigned: [test_topic-7, test_topic-6, test_topic-5, test_topic-4]
[org.springframework.kafka.KafkaListenerEndpointContainer#1-0-C-1] INFO o.s.k.l.KafkaMessageListenerContainer.info - my-consumer: partitions assigned: [test_topic-3, test_topic-2, test_topic-1, test_topic-0]
我正在使用 spring 啟動 2.2.2
依賴:spring-kafka
您可能希望使用自動裝配的AdminClient
使用以下方法鏈:
public Collection<MemberDescription> members()
throws InterruptedException, ExecutionException, TimeoutException
{
String group = "my-consumer";
List<String> groups = Collections.singletonList(group);
return adminClient
.describeConsumerGroups(groups) // DescribeConsumerGroupsResult
.describedGroups() // Map<String, KafkaFuture<ConsumerGroupDescription>>
.get(group) // KafkaFuture<ConsumerGroupDescription>
.get(2, TimeUnit.SECONDS) // ConsumerGroupDescription
.members(); // Collection<MemberDescription>
}
MemberDescription
的返回集合包含您的消費者。 object 提供以下“吸氣劑”:
CLIENT-ID
條目的MemberDescription::clientId
。COMSUMER-ID
條目的MemberDescription::consumerId
。 KafkaFuture
包裝背后的原因是支持 Java-8 方式實現java.util.concurrent.Future<T>
的異步編程風格。 您可以使用 ( .get(2, TimeUnit.SECONDS)
) 阻止希望結果的調用(當時應該可用),也可以通過 Java-8 期貨使用適當的異步方式。
我認為客戶端上沒有consumer-id
。 您可以從metrics
中獲取client-id
:
@SpringBootApplication
public class So61616543Application {
public static void main(String[] args) {
SpringApplication.run(So61616543Application.class, args).close();
}
@KafkaListener(id = "so61616543", topics = "so61616543")
public void listen(String in) {
System.out.println(in);
}
@Bean
public NewTopic topic() {
return TopicBuilder.name("so61616543").partitions(1).replicas(1).build();
}
@Bean
public ApplicationRunner runner(KafkaListenerEndpointRegistry registry) {
return args -> {
registry.getListenerContainer("so61616543").metrics()
.forEach((clientId, metrics) -> {
System.out.println(clientId);
metrics.forEach((key, value) -> System.out.println(key + ":" + value));
});
};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.