简体   繁体   English

spring boot kafka中基于consumer record key的多个consumer

[英]Multiple consumers based on consumer record key in spring boot kafka

I want to list kafka topic based on the consumer record key.我想根据消费者记录键列出kafka主题。 Right now I have consumer and based on the condition I am processing the record现在我有消费者并根据我处理记录的条件

@KafkaListener(topics = "topic",
        containerFactory = "kafkaListenerStringContainerFactory")
public void listenasString(ConsumerRecord<String, String> cr) {
  if (cr.key().equals("A")) {
    //do some processing
  } else if (cr.key().equals("B")) {
    //do some processing
  }

}

Is it possible to have multiple consumers to listen to same topic based on the key?是否可以让多个消费者根据密钥收听同一主题?

I'm not sure what you want is possible我不确定你想要什么是可能的

have multiple consumers to listen to same topic让多个消费者收听同一主题

Yes, this is possible是的,这是可能的

based on the key基于密钥

This is not, because a key is not a queryable.这不是,因为键不是可查询的。 You would need to compute the partition of that key , then you would need to assign the consumer to that partition .您需要计算该键的分区,然后您需要将使用者分配到该分区

Outside of Spring, you can initialize DefaultPartitioner and use consumer.assign to make this work在 Spring 之外,您可以初始化DefaultPartitioner并使用consumer.assign来完成这项工作

From there I would suggest using one consumer thread per partition, and your secondary if statements would need to move unless there's multiple keys in the same partitions (which is possible)从那里我建议每个分区使用一个消费者线程,除非同一分区中有多个键(这是可能的),否则您的辅助 if 语句需要移动

将 kafka 侦听器并发设置为大于 1

spring.kafka.listener.concurrency=3 

You can use streams to create two topics based on keys and run a consumer for each of these topics.您可以使用流基于键创建两个主题,并为每个主题运行一个使用者。 But if you want that to be in the same topic then @criket_007 answer is correct, this is not possible.但是,如果您希望它属于同一主题,那么@criket_007 的答案是正确的,这是不可能的。

Check Kafka Stream Branch https://docs.confluent.io/current/streams/developer-guide/dsl-api.html#stateless-transformations检查 Kafka Stream 分支https://docs.confluent.io/current/streams/developer-guide/dsl-api.html#stateless-transformations

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

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