Skip to content

9.3.1 Setting up Spring for Kafka messaging

To start using Kafka for messaging, you’ll need to add the appropriate dependencies to your build. Unlike the JMS and RabbitMQ options, however, there isn’t a Spring Boot starter for Kafka. Have no fear, though; you’ll only need one dependency, shown next:

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

This one dependency brings everything you need for Kafka to the project. What’s more, its presence will trigger Spring Boot autoconfiguration for Kafka that will, among other things, arrange for a KafkaTemplate in the Spring application context. All you need to do is inject the KafkaTemplate and go to work sending and receiving messages.

Before you start sending and receiving messages, however, you should be aware of a few properties that will come in handy when working with Kafka. Specifically, KafkaTemplate defaults to work with a Kafka broker on localhost, listening on port 9092.

It’s fine to start up a Kafka broker locally while developing an application, but when it’s time to go to production, you’ll need to configure a different host and port.

INSTALLING A KAFKA CLUSTER You’ll need a Kafka cluster available if you want to run the examples presented in this chapter. The Kafka documentation at https://kafka.apache.org/quickstart, is a great place to start to learn how to run Kafka locally on your machine.

The spring.kafka.bootstrap-servers property sets the location of one or more Kafka servers used to establish an initial connection to the Kafka cluster. For example, if one of the Kafka servers in the cluster is running at kafka.tacocloud.com and listening on port 9092, you can configure its location in YAML like this:

yaml
spring:
  kafka:
    bootstrap-servers:
    - kafka.tacocloud.com:9092

But notice that spring.kafka.bootstrap-servers is plural and accepts a list. As such, you can provide it with multiple Kafka servers in the cluster, as shown next:

yaml
spring:
  kafka:
    bootstrap-servers:
    - kafka.tacocloud.com:9092
    - kafka.tacocloud.com:9093
    - kafka.tacocloud.com:9094

These configurations are for Kafka bootstrap servers on a host named kafka.tacocloud.com. If you’re running your Kafka cluster locally (which is likely during development), then you’ll want to use localhost instead, shown next:

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

With Kafka set up in your project, you’re ready to send and receive messages. You’ll start by sending TacoOrder objects to Kafka using KafkaTemplate.

Released under the MIT License.