问题
I am trying to test spring kafka(2.2.5.RELEASE) where when producer send message with kafkatemplate, i like to know if that message was sent successfully or not. Based on that I would like to update the db record for that message id. What is the best practice to handle this scenario?
Here is the sample code which checks success or failure
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("test_topic", key, userMsg);
SendResult<String, String> result = null;
try {
result = future.get(10000, TimeUnit.MILLISECONDS);
LOGGER.info("Send Result : {}", result);
LOGGER.info("Saving entry in db");
messageRepo.save(result.getProducerRecord().key().toString(),result.getProducerRecord().value().toString());
} catch (Exception e) {
LOGGER.error("Error publishing message ", e);
messageRepo.save(result.getProducerRecord().key().toString(),result.getProducerRecord().value().toString());
}
回答1:
The send()
operations return a ListenableFuture<>
which is completed asynchronously.
If you want to block the calling thread to get the result, use
future.get(timeout, TimeUnit.MILLISECONDS);
来源:https://stackoverflow.com/questions/60725906/how-to-verify-sprng-kafka-producer-has-successfully-sent-message-or-not