KafkaTemplate#send asynchronously publishes a key and value to a selected Kafka topic. It hides the need to construct a ProducerRecord, accepting the topic, key, and value directly. section 12.2.1
A typical processing flow uses the method to route and optionally duplicate an event:
- Choose an accepted or rejected topic after evaluating the loan application. section 12.2.1
- Send the processed application with its customer ID as key and the application as value. section 12.2.1
- Optionally send the same processed application to a quality-assurance topic. section 12.2.1
- Capture the returned ListenableFuture when delivery results matter; attach a callback instead of blocking with get(). section 12.2.1
Routing a processed loan
kafkaTemplate.send(topicToSend, processedLoan.getCustomerId(), processedLoan); section 12.2.1
Listing 12.7 Loan processing handling in the method
@KafkaListener(topics = "${loan.app.input.topic}", #1
groupId = "${application.group}") #2
public void doProcessLoanApplication(LoanApplication loanApplication) {
boolean loanApproved = debtRatio <= 0.33 &&
loanApplication.getCreditRating() > 650;
String topicToSend = loanApproved ? acceptedLoansTopic :
rejectedLoansTopic; #3
LoanApplication processedLoan = LoanApplication.Builder.newBuilder(
loanApplication).withApproved(loanApproved).build();
kafkaTemplate.send(topicToSend, processedLoan.getCustomerId(),
processedLoan); #4
if (random.nextInt(100) > 75) {
kafkaTemplate.send(qaLoansTopic, processedLoan.getCustomerId(),
processedLoan); #5
}
}
Inspect the complete processing method, including topic selection, key construction, the primary send, and optional QA forwarding. section 12.2.1
