π¨ Producing and Consuming Messages in Apache Kafka using Java
Apache Kafka is a high-performance, distributed event streaming platform that enables applications to publish and subscribe to data streams in real time.
In this post, we’ll walk through how to set up Kafka locally, and create a simple Java producer and consumer to exchange messages.
⚙️ Step 1 — Download Apache Kafka
Download the latest stable version of Apache Kafka from the official website:
π https://kafka.apache.org/downloads
After downloading, extract the .tgz file:
π Step 2 — Start Zookeeper and Kafka Server
Kafka requires Zookeeper to manage its brokers (in older versions).
Start both Zookeeper and Kafka services using the default configuration files.
✅ Once both are running, Kafka is ready to accept producer and consumer connections.
π¦ Step 3 — Create a Maven Project
Create a new Java Maven project and add the following dependency to your pom.xml file:
π‘ Note: This example uses an older Kafka client (0.10.x).
For newer versions, useorg.apache.kafka:kafka-clients(post-0.11), but the logic remains similar.
π§ Step 4 — Write Java Code for Producer and Consumer
Below is a simple example that sends a message to a Kafka topic (order) and then consumes it.
π§© MyKafkaConsumer.java
π§Ύ Step 5 — Example Output
When you run the program, the following output will appear on your console:
π Step 6 — Download Full Example
You can download or clone the working example from GitHub:
π https://github.com/kkvinodkumaran/kafka
π§ How It Works — High-Level Flow
Here’s the conceptual flow of how this example operates:
-
Producer connects to the broker and publishes the message.
-
Broker stores the message in the specified topic partition.
-
Consumer subscribes to that topic and retrieves messages sequentially.
π§© Key Takeaways
| Concept | Description |
|---|---|
| Producer | Sends data to Kafka topics |
| Consumer | Reads data from Kafka topics |
| Broker | Kafka server that stores and delivers messages |
| Topic | Named channel for message streams |
| Zookeeper | Manages broker metadata (for older Kafka versions) |
Reference: Kafka