spring Sping Boot Kafka配置

dl5txlt9  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(119)

如果您查看官方文档(https://docs.spring.io/spring-kafka/reference/kafka/receiving-messages/listener-annotation.html)和互联网上几乎所有的示例,Sping Boot 中的 KafkaListenerContainerFactory 是这样配置的:

@Configuration
@EnableKafka
public class KafkaConfig {

    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, String>>
                        kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
                                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(3);
        factory.getContainerProperties().setPollTimeout(3000);
        return factory;
    }

    @Bean
    public ConsumerFactory<Integer, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

}

字符串
请注意,kafkaListenerContainerFactory() 方法不是接受 ConsumerFactory bean作为参数,而是调用 consumerFactory() 方法,创建 ConsumerFactory 类的第二个示例,并破坏在此方法旁边声明的bean的目的。
为什么要这样做?

pinkon5k

pinkon5k1#

这是不正确的。如果你使用@Configuration而不使用proxyBeanMethods = false

/**
 * Specify whether {@code @Bean} methods should get proxied in order to enforce
 * bean lifecycle behavior, e.g. to return shared singleton bean instances even
 * in case of direct {@code @Bean} method calls in user code. This feature
 * requires method interception, implemented through a runtime-generated CGLIB
 * subclass which comes with limitations such as the configuration class and
 * its methods not being allowed to declare {@code final}.
 * <p>The default is {@code true}, allowing for 'inter-bean references' via direct
 * method calls within the configuration class as well as for external calls to
 * this configuration's {@code @Bean} methods, e.g. from another configuration class.
 * If this is not needed since each of this particular configuration's {@code @Bean}
 * methods is self-contained and designed as a plain factory method for container use,
 * switch this flag to {@code false} in order to avoid CGLIB subclass processing.
 * <p>Turning off bean method interception effectively processes {@code @Bean}
 * methods individually like when declared on non-{@code @Configuration} classes,
 * a.k.a. "@Bean Lite Mode" (see {@link Bean @Bean's javadoc}). It is therefore
 * behaviorally equivalent to removing the {@code @Configuration} stereotype.
 * @since 5.2
 */
boolean proxyBeanMethods() default true;

字符串
然后这个类中的所有@Bean方法都被代理,每当我们调用它们时,示例只创建一次。
参数注入确实更好,因为我们不通过代理,但这已经超出了Spring for Apache Kafka的范围。我相信那些bean方法调用风格的示例更适合理解而不是性能等。
这也是一个事实,使用Sping Boot ,你可能不需要那些工厂bean,因为它们只是自动配置的。然而,这并不意味着你总是使用Sping Boot 。因此,普通的Spring for Apache Kafka示例往往充满了信息。

相关问题