A hands-on Spring Boot demo that produces and consumes messages with Apache Kafka using the publish/subscribe model.
This tutorial covers the basics of Kafka and walks through a small Java app with a REST producer, a Kafka consumer, and an endpoint to inspect consumed messages.
- Produce messages to a Kafka topic over HTTP
- Consume messages from the same topic with
@KafkaListener - List messages the consumer has received so far
- JSON serialization for producer payloads (
Userobjects)
| Component | Version / detail |
|---|---|
| Java | 8 |
| Spring Boot | 2.2.4.RELEASE |
| Spring Kafka | (managed by Boot) |
| Kafka broker | localhost:9092 |
| Topic | myTopic |
| Consumer group | kafka-sandbox |
| App port | 8081 |
- JDK 8+
- Maven 3.x
- Apache Kafka (classic Zookeeper mode — download from kafka.apache.org/downloads)
spring-boot-with-apache-kafka/
└── spring-boot-kafka/
├── pom.xml
└── src/main/java/com/chat/kafka/
├── SpringBootKafkaApplication.java
├── controller/KafkaController.java
├── producer/ProducerConfiguration.java
├── consume/ConsumerConfiguration.java
├── consume/MyTopicConsumer.java
└── model/User.java
Extract Kafka to a directory of your choice. Commands below assume you are inside the Kafka bin folder (use the scripts under bin/windows on Windows).
./zookeeper-server-start.sh ../config/zookeeper.propertiesIn a second terminal:
./kafka-server-start.sh ../config/server.propertiesIn a third terminal:
./kafka-topics.sh --create --topic myTopic \
--zookeeper localhost:2181 \
--replication-factor 1 \
--partitions 1Note: Newer Kafka versions prefer
--bootstrap-server localhost:9092instead of--zookeeper. Use the flag that matches your Kafka install.
cd spring-boot-kafka
mvn clean install
mvn spring-boot:runOr import spring-boot-kafka into your IDE and run SpringBootKafkaApplication.
The app listens on http://localhost:8081.
| Action | Method | URL |
|---|---|---|
| Produce a message | GET |
http://localhost:8081/kafka/produce?message=Hello%20Kafka |
| List consumed msgs | GET |
http://localhost:8081/kafka/messages |
- Open
http://localhost:8081/kafka/messages— the list is empty until something is produced. - Produce a message:
http://localhost:8081/kafka/produce?message=Message%20sent%20by%20my%20App! - Call
/kafka/messagesagain — you should see the consumed payload(s).
You can use a browser or Postman for both requests.
- Producer —
GET /kafka/producebuilds aUser(name+message) and sends it tomyTopicviaKafkaTemplate. - Consumer —
MyTopicConsumerlistens onmyTopic(groupkafka-sandbox) and stores each message in memory. - Read API —
GET /kafka/messagesreturns that in-memory list.
Broker address is configured in code as localhost:9092 (ProducerConfiguration / ConsumerConfiguration).
This project is provided as a learning sample. Feel free to fork and adapt it.