问题
I'm trying to create a consumer client in Java. I realized the poll() function is depreciated. What are the alternatives to listen to a topic of Kafka?
My code:
KafkaConsumer< String, UserSegmentPayload > kc = new KafkaConsumer<>(props2);
kc.subscribe(Collections.singletonList(topicName));
while (true) {
ConsumerRecords<String, UserSegmentPayload> records = kc.poll(100);
for (ConsumerRecord<String, UserSegmentPayload> record : records) {
System.out.printf("offset = %d, key = %s, value = %s\n",
record.offset(), record.key(), record.value());
}
}
回答1:
The reason poll()
and poll(long)
are deprecated is that they may block indefinitely (even in the second case, where a timeout is specified). The root cause for this behaviour is that an initial metadata update in those methods may block forever (see here). Instead, you should use the poll(Duration)
-method of the KafkaConsumer
. So, in your code, all you have to do is to replace kc.poll(100)
with kc.poll(Duration.ofMillis(100))
.
来源:https://stackoverflow.com/questions/59943786/kafka-what-are-the-better-alternatives-than-poll-to-listen-to-a-topic-in-jav