Obtaining the Consumer group.id

在多个容器中运行相同的侦听器代码时,可能需要确定记录来自哪个容器(由其 group.id 消费者属性标识)。

When running the same listener code in multiple containers, it may be useful to be able to determine which container (identified by its group.id consumer property) that a record came from.

你可以在侦听器线程上调用 KafkaUtils.getConsumerGroupId() 来执行此操作。或者,你可以在方法参数中访问组 ID。

You can call KafkaUtils.getConsumerGroupId() on the listener thread to do this. Alternatively, you can access the group id in a method parameter.

@KafkaListener(id = "id", topicPattern = "someTopic")
public void listener(@Payload String payload, @Header(KafkaHeaders.GROUP_ID) String groupId) {
    ...
}

在接收记录 List<?> 的记录侦听器和批处理侦听器中,这一点是可用的。它在接收 ConsumerRecords<?, ?> 参数的批处理侦听器中是 not 可用的。在这种情况中,使用 KafkaUtils 机制。

This is available in record listeners and batch listeners that receive a List<?> of records. It is not available in a batch listener that receives a ConsumerRecords<?, ?> argument. Use the KafkaUtils mechanism in that case.