【问题标题】:Any possibility that I can provide configuration details at run time to producer and consumer in spring-kafka?我可以在运行时向 spring-kafka 中的生产者和消费者提供配置详细信息吗?
【发布时间】:2021-05-25 13:27:57
【问题描述】:

我们正在使用 Spring Boot 将我们的项目迁移到微服务。我有一个要求,我应该能够使用用户在运行时提供的引导服务器和键值 serdes 等配置详细信息来运行生产者和消费者。

我能够在早期项目中使用 java Apache Kafka API 来做到这一点,但我没有看到任何使用 spring-kafka API 的方法,因为它只允许通过 Spring java 配置定义生产者或消费者相关配置类或 application.properties。

【问题讨论】:

  • 有什么特别的理由选择 spring-kafka 而不是使用现有的 apache kafka api 吗?
  • 整个应用程序(包括其他模块)正在迁移到 Spring Boot。我正在探索是否可以在这里使用 spring boot kafka API,而不是 Apache kafka API?
  • 是的,你绝对可以探索spring-kafka,但就我个人而言,我使用Apache Kafka api只是为了更加独立和解耦。

标签: spring-boot apache-kafka spring-kafka


【解决方案1】:

您可以在运行时为消费者和生产者覆盖您想要的任何属性。

使用ConcurrentKafkaListenerContainerFactory 创建监听容器:

@Autowired
ConcurrentKafkaListenerContainerFactory<String, String> factory;

...

    ConcurrentMessageListenerContainer<String, String> container = factory.createContainer("someTopic");
    container.getContainerProperties()
            .getKafkaConsumerProperties()
            .setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "...");
    ...
    container.getContainerProperties().setMessageListener(someListener);
    container.start();

在生产者端,使用这个构造函数:

/**
 * Create an instance using the supplied producer factory and properties, with
 * autoFlush false. If the configOverrides is not null or empty, a new
 * {@link DefaultKafkaProducerFactory} will be created with merged producer properties
 * with the overrides being applied after the supplied factory's properties.
 * @param producerFactory the producer factory.
 * @param configOverrides producer configuration properties to override.
 * @since 2.5
 */
public KafkaTemplate(ProducerFactory<K, V> producerFactory, @Nullable Map<String, Object> configOverrides) {
    this(producerFactory, false, configOverrides);
}

【讨论】:

  • 嗨,加里。感谢您的回复。你能对此有所了解吗?只是想确定一下,在启动 Spring Boot 应用程序后,是否可以在运行时按需创建、启动或停止新的生产者或消费者。
  • 是的,当然,当你不再需要它们时,使用上面的代码创建并启动一个新的容器或模板,stop() 容器和destroy() 模板(关闭它的生产者) .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 2023-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多