liveBook · Manning

KafkaTemplate#send

As explained in Kafka Streams in Action, Second Edition

KafkaTemplate#send is a Spring Kafka method that asynchronously sends a key and value to a specified Kafka topic.

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

How Kafka Streams in Action, Second Edition covers it

How deep it goes
Explains arguments, ProducerRecord convenience, futures, callbacks, and blocking, but omits broker-delivery implementation details.
Examples
Uses processed loan applications, customer IDs, approval or rejection topics, and an optional QA topic.
What it assumes
Assumes familiarity with KafkaProducer records and basic Spring Kafka listener components.
What you can do after
Apply KafkaTemplate#send to publish keyed values asynchronously and handle results without blocking.
How it connects
Connects KafkaTemplate#send with KafkaProducer, ProducerRecord, Kafka topics, ListenableFuture, and asynchronous callbacks.

This explainer was generated by Manning's knowledge graph from the text of Kafka Streams in Action, Second Edition. The section links point to the parts of the book it draws on.