问题描述
我正在用 Spring Boot 编写一个应用程序,以便写入 Kafka 我这样做:
I'm writing an application with Spring Boot so to write to Kafka I do:
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
然后在我的方法中:
kafkaTemplate.send(topic, data)
但我觉得我只是依靠它来工作,我怎么知道这是否有效?如果它是异步的,返回 200 代码并希望它起作用是一个好习惯吗?我糊涂了.如果Kafka不可用,这不会失败吗?不应该提示我捕获异常吗?
But I feel like I'm just relying on this to work, how can I know if this has worked? If it's asynchronous, is it a good practice to return a 200 code and hoped it did work? I'm confused. If Kafka isn't available, won't this fail? Shouldn't I be prompted to catch an exception?
推荐答案
是的,如果 Kafka 不可用,那个 .send()
调用将失败,但如果你异步发送,没有人将被通知.您可以指定要在未来最终完成时执行的回调.完整的接口规范在这里:https://kafka.apache.org/20/javadoc/org/apache/kafka/clients/producer/Callback.html
Yes, if Kafka is not available, that .send()
call will fail, but if you send it async, no one will be notified. You can specify a callback that you want to be executed when the future finally finishes. Full interface spec here: https://kafka.apache.org/20/javadoc/org/apache/kafka/clients/producer/Callback.html
来自这里的官方 Kafka javadoc:https://kafka.apache.org/20/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html
From the official Kafka javadoc here: https://kafka.apache.org/20/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html
完全非阻塞的使用可以利用回调参数来提供将在请求完成时调用的回调.
ProducerRecord<byte[],byte[]> record = new ProducerRecord<byte[],byte[]>("the-topic", key, value);
producer.send(myRecord,
new Callback() {
public void onCompletion(RecordMetadata metadata, Exception e) {
if(e != null) {
e.printStackTrace();
} else {
System.out.println("The offset of the record we just sent is: " + metadata.offset());
}
}
});
这篇关于断言卡夫卡发送工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!