liveBook · Manning

KafkaTemplate

As explained in Spring in Action, Sixth Edition

KafkaTemplate is a Spring for Apache Kafka API class that sends records to and receives records from Kafka topics.

KafkaTemplate is Spring for Apache Kafka’s typed client for sending domain objects to Kafka topics. Adding the Spring Kafka dependency triggers Spring Boot autoconfiguration, which places a KafkaTemplate in the application context for injection. section 9.3.1 section 9.3.2

Use KafkaTemplate’s send methods to provide the message details that matter:

  • Specify a topic and payload; optionally provide a key, partition, timestamp, ProducerRecord, or Message. section 9.3.2
  • Focus on the topic and payload for straightforward publishing; partitions and keys add routing information without changing the basic usage. section 9.3.2
  • Use sendDefault when a default topic is configured instead of passing the topic to every call. section 9.3.2

Publishing an order

Inject KafkaTemplate<String, TacoOrder> into a service, then call kafkaTemplate.send("tacocloud.orders.topic", order) from sendOrder. The generic type lets the template send the TacoOrder directly. section 9.3.2

<dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>

Add the Spring Kafka dependency that enables the Kafka integration and related Boot autoconfiguration. section 9.3.1

spring:
  kafka:
    bootstrap-servers:
    - localhost:9092

Configure localhost:9092 for a locally running Kafka broker; production deployments require different bootstrap-server settings. section 9.3.1

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains dependency setup, broker configuration, typed send signatures, optional record fields, and a service implementation.
Examples
Uses a TacoOrder service, the tacocloud.orders.topic topic, localhost:9092, and a sendDefault variant.
What it assumes
Assumes a Kafka cluster or local broker and teaches dependency, bootstrap-server, injection, and basic sending setup.
What you can do after
Apply it via Spring Kafka by injecting a typed template and sending domain objects to named or configured default topics.
How it connects
Connects KafkaTemplate with Spring Boot autoconfiguration, Kafka topics, partitions, keys, ProducerRecord, JMS, and RabbitMQ.

Also explained in

Compare how 2 books explain KafkaTemplate →

Related concepts

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