我已经订阅了以下Kafka主题。仅在为使用者分配了分区之后,我才需要运行一些逻辑。
无论我等待多长时间,consumer.assignment()
都会作为空集返回。如果我没有while循环,然后执行consumer.poll()
,则确实从该主题获取了记录。有人可以告诉我为什么会这样吗?
consumer.subscribe(topics);
Set<TopicPartition> assigned=Collections.emptySet();
while(isAssigned) {
assigned = consumer.assignment();
if(!assigned.isEmpty()) {
isAssigned= false;
}
}
//consumer props
Properties props = new Properties();
props.put("bootstrap.servers", "xxx:9092,yyy:9092");
props.put("group.id", groupId);
props.put("enable.auto.commit", "false");
props.put("session.timeout.ms", "30000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "io.confluent.kafka.serializers.KafkaAvroDeserializer");
props.put("schema.registry.url", "http://xxx:8081");
props.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.put("max.poll.records", "100");
答案 0 :(得分:0)
在您致电poll()
之前,消费者只是闲着。
仅在调用poll()
之后,它将启动与群集的连接,获取分配的分区并尝试获取消息。
Javadoc中提到了这一点:
订阅一组主题后,消费者将自动 调用poll(Duration)时加入该组。
一旦开始调用poll()
,就可以使用assignment()
甚至注册ConsumerRebalanceListener
来通知从消费者实例中分配或撤销分区的时间。