liveBook · Manning

KafkaTemplate

As explained in Kafka Streams in Action, Second Edition

KafkaTemplate is a Spring Kafka class that provides high-level methods for sending records to Kafka topics.

KafkaTemplate is the Spring Kafka producer-facing dependency used to publish application records. Declare it with key and value types, inject it into a Spring component, and use it where a listener has finished processing an event and must emit the result to another topic. section 12.2.1

Its core call is send(topic, key, value). The topic selects the destination; the key can be a customer ID; and the value is the processed event. A loan processor sends an approved or rejected LoanApplication to a selected output topic, then may also send the same result to a QA topic. section 12.2.1

Publish with completion handling

Keep the result returned by send, then attach a callback. On success, read RecordMetadata to log the produced topic, offset, and timestamp. On failure, log the producing error; no produced offset or timestamp is available in that case. section 12.2.2

A single KafkaTemplate can be shared by concurrent listener threads because its underlying KafkaProducer is thread safe. Listener methods should remain stateless when concurrency is increased; shared mutable state requires synchronization for deterministic results. 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

The listing captures the future returned by send and attaches a callback for produced-record metadata or errors. section 12.2.2

How Kafka Streams in Action, Second Edition covers it

How deep it goes
Explains constructor injection, send arguments, completion callbacks, and concurrent sharing; defers Java threading and synchronization.
Examples
Uses a loan processor that routes approved or rejected applications and optionally copies results to a QA topic.
What it assumes
Assumes basic Java threading knowledge while briefly defining thread safety and warning against shared mutable listener state.
What you can do after
Apply it via Spring Kafka to send keyed records and attach callbacks that log broker-produced metadata or errors.
How it connects
Connects KafkaTemplate with KafkaListener, KafkaProducer, topics, partitions, ListenableFuture, SendResult, and RecordMetadata.

Also explained in

Compare how 2 books explain KafkaTemplate →

Related concepts

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.