【问题标题】:@KafkaListener vs ConsumerFactory groupId@KafkaListener vs ConsumerFactory groupId
【发布时间】:2020-09-22 08:34:06
【问题描述】:

我遵循了 baeldung.com 的“Intro to Apache Kafka with Spring”教程。 我用kafkaConsumerFactory 方法设置了一个KafkaConsumerConfig 类:

private ConsumerFactory<String, String> kafkaConsumerFactory(String groupId) {
    Map<String, Object> props = new HashMap<>();
    ...
    props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
    ...
    return new DefaultKafkaConsumerFactory<>(props);
}

还有两个“自定义”工厂:

@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> fooKafkaListenerContainerFactory() {
    return kafkaListenerContainerFactory("foo");
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> barKafkaListenerContainerFactory() {
    return kafkaListenerContainerFactory("bar");
}

在MessageListener 类中,我使用@KafkaListener 注释来注册具有给定groupId 的消费者来监听主题:

@KafkaListener(topics = "${message.topic.name}", groupId = "foo", containerFactory = "fooKafkaListenerContainerFactory")
public void listenGroupFoo(String message) {
    System.out.println("Received Message in group 'foo': " + message);
    ...
}

@KafkaListener(topics = "${message.topic.name}", groupId = "bar", containerFactory = "barKafkaListenerContainerFactory")
public void listenGroupBar(String message) {
    System.out.println("Received Message in group 'bar': " + message);
    ...
}

这样就有两组消费者,一组是 groupId “foo”,另一组是 groupId “bar”。

现在,如果我以这种方式将“foo”消费者的容器工厂从 fooKafkaListenerContainerFactory 更改为 barKafkaListenerContainerFactory

@KafkaListener(topics = "${message.topic.name}", groupId = "foo", containerFactory = "barKafkaListenerContainerFactory")
public void listenGroupFoo(String message) {
    ...
}

KafkaListener 的groupId 和容器工厂的groupId 之间似乎不兼容,但没有任何变化。 所以,我想了解的是props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);property 做了什么以及为什么它似乎没有被考虑。

【问题讨论】:

    标签: apache-kafka kafka-consumer-api spring-kafka


    【解决方案1】:

    工厂groupId 是默认值,仅在@KafkaListener 上没有groupId(或id)时使用。

    在早期版本中,只能在工厂上设置 groupId,这意味着如果需要不同的组,您需要为每个侦听器单独的工厂,这违背了可用于多个侦听器的工厂的想法。

    查看 javadocs...

    /**
     * Override the {@code group.id} property for the consumer factory with this value
     * for this listener only.
     * <p>SpEL {@code #{...}} and property place holders {@code ${...}} are supported.
     * @return the group id.
     * @since 1.3
     */
    String groupId() default "";
    
    /**
     * When {@link #groupId() groupId} is not provided, use the {@link #id() id} (if
     * provided) as the {@code group.id} property for the consumer. Set to false, to use
     * the {@code group.id} from the consumer factory.
     * @return false to disable.
     * @since 1.3
     */
    boolean idIsGroup() default true;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 2011-03-08
      • 1970-01-01
      • 2020-09-10
      • 2019-11-19
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多