ListenableFuture represents the eventual result of an asynchronous Kafka produce request. KafkaTemplate.send returns a ListenableFuture<SendResult<K, V>>, allowing a loan-processing service to send a processed record without immediately waiting for the broker response. section 12.2.1
Calling get waits until the produce request completes and blocks the application thread. Prefer attaching a callback when later work depends on the outcome, so success and failure handling run asynchronously after the send completes. section 12.2.1 section 12.2.2
A callback handles both completion paths:
- onSuccess receives SendResult, whose RecordMetadata supplies the produced record's topic, offset, and timestamp for logging or follow-up work. section 12.2.2
- onFailure receives the exception, allowing production problems to be logged rather than silently ignored. section 12.2.2
- addCallback registers the callback on the ListenableFuture returned by KafkaTemplate.send. section 12.2.2
Capture send metadata without blocking
After routing a processed loan to its accepted or rejected topic, keep the future returned by kafkaTemplate.send and add a ListenableFutureCallback. The success path can log the broker-assigned offset and timestamp; the failure path can log the production error. The listener can continue rather than waiting on get. section 12.2.1 section 12.2.2
Listing 12.16 Adding a callback for notification of completed produce requests
ListenableFuture<SendResult<String, LoanApplication>>
produceResult = #1
kafkaTemplate.send(topicToSend,
processedLoan.getCustomerId(),
processedLoan);
produceResult.addCallback(produceCallback); #2
This listing shows the essential sequence: store KafkaTemplate.send's ListenableFuture, then register a completion callback with addCallback. section 12.2.2
