Tip #39 (Spring) Ensure Changes Only on Successful Kafka Message Delivery
NB: A while back, I shared a similar tip using ListenableFuture
, but in Spring Boot 3.0.0, ListenableFuture
was deprecated.
Imagine this: you’re sending messages to a Kafka topic, and you want to update a job’s status only if the message is delivered. To ensure that happens, you’ll need to check the result of your CompletableFuture
.
Here’s the code:
your class {
var completableFuture = kafkaProducer.send(event, topic);
completableFuture
.thenAcceptAsync(result -> myJob.setStatus(NEW_STATUS))
.exceptionallyAsync(this::onFailure);
completableFuture.join();
}
private Void onFailure(@NotNull Throwable t) {
log.warn("Unable to send message to Kafka. cause {}", t.getMessage());
return null;
}
Now, you’ll only update the job status if the Kafka message is delivered successfully. Notice we’re using completableFuture.join();
to wait for completion—necessary to capture the response.
Happy coding!