繁体   English   中英

是否可以使用键和分区来消费 kafka 消息?

[英]Is it possible to consume kafka messages using key and partition?

我正在使用kafka_2.12版本2.3.0 ,我使用分区和密钥将数据发布到 kafka 主题中。 我需要找到一种方法,使用它可以使用键和分区组合来使用来自主题的特定消息。 这样我就不必消耗所有消息并迭代正确的消息。

现在我只能做到这一点

KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props)
consumer.subscribe(Collections.singletonList("topic"))
ConsumerRecords<String, String> records = consumer.poll(100)
def data = records.findAll {
    it -> it.key().equals(key)
}

您不能“通过密钥从 Kafka 获取消息”。

如果可行,一种解决方案是拥有与键一样多的分区,并始终将键的消息路由到同一分区。

消息键作为分区

kafkaConsumer.assign(topicPartitions);
    kafkaConsumer.seekToBeginning(topicPartitions);

    // Pull records from kafka, keep polling until we get nothing back
    final List<ConsumerRecord<byte[], byte[]>> allRecords = new ArrayList<>();
    ConsumerRecords<byte[], byte[]> records;
    do {
        // Grab records from kafka
        records = kafkaConsumer.poll(2000L);
        logger.info("Found {} records in kafka", records.count());

        // Add to our array list
        records.forEach(allRecords::add);

    }
    while (!records.isEmpty());

仅使用主题名称访问主题的消息

KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
     consumer.subscribe(Arrays.asList(<Topic Name>,<Topic Name>));
     while (true) {
         ConsumerRecords<String, String> records = consumer.poll(100);
         for (ConsumerRecord<String, String> record : records)
             System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
     }

有两种消费主题/分区的方法是:

  1. KafkaConsumer.assign(): 文档链接
  2. KafkaConsumer.subscribe(): 文档链接

因此,您无法通过密钥获取消息。

如果您没有扩展分区的计划,请考虑使用 assign() 方法。 因为带有特定键的所有消息都会 go 到同一个分区。

如何使用:

KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
TopicPartition partition = new TopicPartition("some-topic", 0);
consumer.assign(Arrays.asList(partition));

while(true){
    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
    String data = records.findAll {
        it -> it.key().equals(key)
    }
}

暂无
暂无

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

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