使用KafkaProperties配置多个Kafka主题名称的最佳方法是什么

时间:2020-05-21 11:38:13

标签: java spring spring-kafka

我们有一个应用程序,它将通过kafka与不同的服务进行通信。例如,我需要3个消费者(最有可能使用相同的groupId)和3个生产者,每个生产者都从不同的主题中读取和编写内容。我想利用KafkaProperties类来做到这一点。

监听器

@Component
@RequiredArgsConstructor // lombok
public class MyKafkaListener {

  @NonNull
  private final EventProcessingService eventProcessingService;

  @NonNull
  private final KafkaProperties kafkaProperties;

  @KafkaListener(topics = #{__kafkaProperties.???})
  public void listenMessageA(final ConsumerRecord<String, MessageA> consumerRecord) {
      // Delegate to eventProcessingService
  }

  @KafkaListener(topics = #{__kafkaProperties.???})
  public void listenMessageB(final ConsumerRecord<String, MessageB> consumerRecord) {
      // Delegate to eventProcessingService
  }

  @KafkaListener(topics = #{__kafkaProperties.???})
  public void listenMessageC(final ConsumerRecord<String, MessageC> consumerRecord) {
      // Delegate to eventProcessingService
  }

}

发布者

@Component
@RequiredArgsConstructor // lombok
public class MyKafkaPublisher<T> {

  @NonNull
  private final KafkaTemplate<String, T> kafkaTemplate;

  @NonNull
  private final KafkaProperties kafkaProperties;

  public void sendMessageX(final MessageX messageX) {
      kafkaTemplate.send(kafkaProperties.???, messageX);
  }

  public void sendMessageY(final MessageY messageY) {
      kafkaTemplate.send(kafkaProperties.???, messageY);
  }

  public void sendMessageZ(final MessageZ messageZ) {
      kafkaTemplate.send(kafkaProperties.???, messageZ);
  }

}

application.yml的片段

spring:
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      groupId: myGroupId
      properties:
        someConsumerProp: someValue
        # Should I add my consumer topic names here?
        topicForA: myFavTopicA
        topicForB: myFavTopicB
        topicForC: myFavTopicC
    producer:
      retries: 10
      properties:
        someProducerProp: someValue
        # Should I add my producer topic names here?
        topicForX: myFavTopicX
        topicForY: myFavTopicY
        topicForZ: myFavTopicZ
    properties:
      someCommonProp: someValue
      # Or may be all topic names here?
      listener.topicForA: myFavTopicA
      listener.topicForB: myFavTopicB
      listener.topicForC: myFavTopicC
      publisher.topicForX: myFavTopicX
      publisher.topicForY: myFavTopicY
      publisher.topicForZ: myFavTopicZ
    template:
      # Bonus question: What is the usage of this property?
      default-topic: myDefTopic

我想知道由???的作者建议的替换上述类中的spring-kafka的最佳方法是什么,这样我就不必写任何额外的{{1} }类或在任何地方使用@ConfigurationProperties,但同时要通过阅读@Value本身来保持主题名称的思想清晰。还是作者提供了解决这种情况的其他方法?

1 个答案:

答案 0 :(得分:1)

引导团队不会将自动配置Properties类视为公共类,并且可以随时更改,因此请注意在应用程序代码中使用它们。

这样重载kafka消费者/生产者/管理员属性有点脏(而且Kafka本身可能会抱怨其配置中的“未知”属性)。

最好创建自己的@ConfigurationProperties类。

要具体回答您的问题,请参阅buildProducerProperties()

相关问题