1

我正在使用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)
}
4

2 回答 2

1

您不能“通过密钥从 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());
     }
于 2019-11-06T07:07:55.980 回答
1

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

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

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

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

如何使用:

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)
    }
}
于 2019-11-06T07:15:42.180 回答