【发布时间】:2020-06-07 10:32:40
【问题描述】:
我不能 for-loop 读取每个分区的 kafka,我不知道我的代码有什么问题,它没有显示我打印的值
示例:我想第一次读取所有偏移分区 0,第二次读取所有偏移分区 1。
(我第一次在stackoverflow上发帖。抱歉交流,希望你能理解我。)
Consumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(topicNames);
List<KafkaTopicDataResponse> results = new ArrayList<>();
try {
Set<TopicPartition> assignments = consumer.assignment();
Object[] assignArray = assignments.toArray();
for (Object topicPartition : assignArray){
boolean flag = true;
int receiveRow = 0;
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
if (flag) {
consumer.seek((TopicPartition) topicPartition,0);
flag = false;
}
for (ConsumerRecord<String, String> record : records) {
receiveRow++;
System.out.printf("offset = %d, partition = %d, key = %s, value = %s%n", record.offset(), record.partition(), record.key(), record.value());
logger.info("count : "+ receiveRow);
}
if (receiveRow >= limitRow){
break;
}
}
}
} catch(Exception e) {
logger.error("Exception occured while consuing messages",e);
}finally {
consumer.close();
}
【问题讨论】:
-
当您执行
consumer.poll()时,您会从分配给该消费者的所有分区中获取消息,而不仅仅是单个分区。 -
是否有单独读取每个分区的特定用例?
-
@JavaTechnical 是的,我想读取每个分区
标签: java spring-boot apache-kafka