我正在编写一些代码来根据分区号和偏移量从Kafka Topic读取特定消息,代码如下
TopicPartition topicPartition = new TopicPartition(this.topicName, partition);
this.consumer.assign(Collections.singletonList(topicPartition));
this.consumer.seek(topicPartition, offset);
ConsumerRecords<Object, Object> records = this.consumer.poll(50000L);
现在,如果在 partition
变量中传递了错误的值,我希望代码抛出错误,但现在它可以工作,只是不获取任何记录。所以我无法区分什么时候没有给定输入的记录,或者给定的输入是错误的。
最佳答案
您可以使用检索集群元数据的方法之一来查找现有分区。
例如,您可以调用partitionsFor()
,或listTopics()
获取主题的现有分区列表。然后您可以检测提供的分区
是否存在。
关于java - 如何在读取 kafka 主题时验证无效的分区名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68903024/