gpt4 book ai didi

java - 创建 Kafka Producer 并调用方法 send()、flush() 和 close() 的正确顺序是什么?

转载 作者:行者123 更新时间:2023-12-01 20:03:01 25 4
gpt4 key购买 nike

我有下面提到的不同模型,我在其中创建 Kafka 生产者并调用不同的方法,但不确定对其进行编程的正确方法是什么,以便流程不应该中断并且性能不应该受到影响。请帮忙。

模型1:

for(int i=1; i < 100; i++){
Producer<String, String> producer = new KafkaProducer<String, String>(props);

ProducerRecord<String, String> data = new ProducerRecord<String, String>(
topicName,
String.valueOf(i)
);

producer.send(data);
producer.close();
}

模型2:

Producer<String, String> producer = new KafkaProducer<String, String>(props);
for(int i=1; i < 100; i++) {

ProducerRecord<String, String> data = new ProducerRecord<String, String>(
topicName,
String.valueOf(i)
);

producer.send(data);
producer.close();
}

模型3:

Producer<String, String> producer = new KafkaProducer<String, String>(props);
for(int i=1; i < 100; i++){

ProducerRecord<String, String> data = new ProducerRecord<String, String>(
topicName,
String.valueOf(i)
);

producer.send(data);
}
producer.close();

模型 4:

for(int i=1; i < 100; i++){
Producer<String, String> producer = new KafkaProducer<String, String>(props);

ProducerRecord<String, String> data = new ProducerRecord<String, String>(
topicName,
String.valueOf(i)
);

producer.send(data);
producer.flush();
producer.close();
}

模型 5:

Producer<String, String> producer = new KafkaProducer<String, String>(props);
for(int i=1; i < 100; i++){
ProducerRecord<String, String> data = new ProducerRecord<String, String>(
topicName,
String.valueOf(i)
);

producer.send(data);
producer.flush();
producer.close();
}

型号 6:

Producer<String, String> producer = new KafkaProducer<String, String>(props);
for(int i=1; i < 100; i++){

ProducerRecord<String, String> data = new ProducerRecord<String, String>(
topicName,
String.valueOf(i)
);

producer.send(data);
producer.flush();
}
producer.close();

最佳答案

Model 3 经过以下更改后似乎应该是正确的

Producer<String, String> producer = new KafkaProducer<String, String>(props);
try {
for (int i = 1; i < 100; i++) {
ProducerRecord<String, String> data = new ProducerRecord<String, String>(topicName, String.valueOf(i));
producer.send(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
producer.close();
}

关于java - 创建 Kafka Producer 并调用方法 send()、flush() 和 close() 的正确顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47832944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com