简体   繁体   English

如何重用 Spring Kafka 代码来设置多个监听器?

[英]How to reuse Spring Kafka code to setup multiple listeners?

If my application has one listener, the case is dead simple:如果我的应用程序有一个侦听器,那么情况就很简单了:

I will configure spring.kafka.* , Spring Boot will parse the configuration to KafkaPropeties and initialize all required beans.我将配置spring.kafka.* , Spring Boot 会将配置解析为KafkaPropeties并初始化所有需要的 bean。

But I have two listeners, let say one saves records to file and second to database.但是我有两个听众,假设一个将记录保存到文件,第二个保存到数据库。 I would like reuse as much as possible Spring Boot conventions.我想尽可能多地重用 Spring 引导约定。

I would like to configure file.kafka.* and db.kafka.* , parse these configuration to 2 KafkaProperties beans:我想配置file.kafka.*db.kafka.* ,将这些配置解析为 2 个KafkaProperties bean:

@ConfigurationProperties("file.kafka")
@Bean(autowireCandidate = false)
KafkaProperties fileKafkaProperties() {
  return new KafkaProperties();
}

@ConfigurationProperties("db.kafka")
@Bean(autowireCandidate = false)
KafkaProperties dbKafkaProperties() {
  return new KafkaProperties();
}

and finally create 2 ConcurrentKafkaListenerContainerFactory : db and file, respectively.最后分别创建 2 个ConcurrentKafkaListenerContainerFactory : db 和 file。

The problem is that to apply KafkaPropeties to ConcurrentKafkaListenerContainerFactory I need ConcurrentKafkaListenerContainerFactoryConfigurer .问题是要将KafkaPropeties应用于ConcurrentKafkaListenerContainerFactory我需要ConcurrentKafkaListenerContainerFactoryConfigurer But the ConcurrentKafkaListenerContainerFactoryConfigurer is not enough public to be initialized with KafkaPropeties .但是ConcurrentKafkaListenerContainerFactoryConfigurer不够公开,无法使用KafkaPropeties进行初始化。

Is there a public access limitation problem on ConcurrentKafkaListenerContainerFactoryConfigurer or do I something wrong? ConcurrentKafkaListenerContainerFactoryConfigurer 是否存在公共访问限制问题,或者我有什么问题?

From KafkaProperties you can build ConsumerFactoryKafkaProperties你可以建立ConsumerFactory

@Bean
@ConditionalOnMissingBean(name="kafkaConsumerFactory")
public ConsumerFactory<String, String> kafkaConsumerFactory(KafkaProperties kafkaProperties) {
return new DefaultKafkaConsumerFactory<>(
        kafkaProperties.buildConsumerProperties(),
        new StringDeserializer(),
        new StringDeserializer());
}

Use ConsumerFactory to build ConcurrentKafkaListenerContainerFactory使用ConsumerFactory构建ConcurrentKafkaListenerContainerFactory

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM