下面是我们之前的配置方式:
yml文件中的配置:
spring.kafka.consumer.bootstrap-servers=localhost:9092
消费者方法加上如下注解:
@KafkaListener(topics = "Topic001")
可以看到,这样是无法对kafka服务地址进行选择的,但是我们发现,在@KafkaListener这个注解中,有一个containerFactory参数,而containerFactory中是可以配置kafka的bootstrapServers的,所以问题就简单啦,我们只需要多建几个containerFactory,配置不通的bootstrapServers,然后在KafkaListener注解上传入不同的containerFactory就好啦。
接下来看实现:
这是我的KafkaConfig
@Configuration @Slf4j @EnableConfigurationProperties({KafkaProducerProperties.class, KafkaConsumerProperties.class, KafkaLocalConsumerProperties.class}) public class KafkaConfig { private final KafkaProducerProperties producerProperties; private final KafkaConsumerProperties defaultConsumerProperties; private final KafkaLocalConsumerProperties localConsumerProperties; public KafkaConfig(KafkaProducerProperties kafkaProperties, KafkaConsumerProperties kafkaConsumerProperties, KafkaLocalConsumerProperties kafkaLocalConsumerProperties) { this.producerProperties = kafkaProperties; this.defaultConsumerProperties = kafkaConsumerProperties; this.localConsumerProperties = kafkaLocalConsumerProperties; } @Bean @Primary public ConsumerFactorydefaultConsumerFactory() { return createConsumerFactory(defaultConsumerProperties); } @Bean public ConsumerFactorylocalConsumerFactory() { return createConsumerFactory(localConsumerProperties); } private DefaultKafkaConsumerFactorycreateConsumerFactory(KafkaBaseConsumerProperties kafkaConsumerProperties) { Mapconfigs = new HashMap