01: Apache Kafka example with Java – getting started tutorial

Apache Kafka with Java getting started tutorial demonstrates how quickly you can get started with Kafka using Docker.

Apache Kafka Example - Getting started Java tutorial

Apache Kafka Example – Getting started Java tutorial

Step 1: Make sure Docker engine is installed on your computer. For example on a Mac OS $ brew cask install docker or on Windows.

Step 2: Start the Docker engine on your operating system.

Kafka services on Docker

Step 3: Create the below docker-compose.yml file to run your Kafka, zookeeper & Apache Kafka Cluster Visualization (AKHQ) services. The images for these services are sourced from Docker hub.

Step 4: Run the Docker container with the above services on the engine via a command-line terminal window where this file docker-compose.yml. Say, if the file is at /Users/yourfolder/projects/simple-kafka/docker-compose.yml

It will take a few minutes to stand up the Docker containers with the requested services for Kafka – Kafka on port 9093, Zookeeper on port 2181 & Apache Kafka Cluster Visualization (AKHQ) on port 9099.

Step 5: You can open a browser to check if AKHQ is running on localhost:9099. This is the Kafka UI.

AKHQ - Apache Kafka UI

AKHQ – Apache Kafka UI

Java Project

Step 6: Create a new maven based Java project simple-kafka. For example, in Intellij IDEA File -> New Project -> Maven.

The pom.xml file with Kafka & logback dependencies:

Step 7: Set up logging xml file logback.xml.

Java Consumer

Step 8: Write a consumer in Java as shown below.

Run the application within intellij IDEA:

Produce a message from akHQ.io UI

Step 9: Go to localhost:9099 akGQ.io & create a new topic named “my-first-topic“. Click on the button “Create a topic” at the right bottom corner.

Step 10: Double click on the topic “my-first-topic” & then click on “Produce to my-first-topic“.

Apache Kafka - Produce a message from akHQ.io

Apache Kafka – Produce a message from akHQ.io

Step 11: Click on the “Produce” button to send the message to the topic.

Java code ConsumerApp.java consumes the message

Step 12: In the console window within Intellij IDEA, the message will be consumed by ConsumerApp.java, which is already running.

Bring down the Docker container

More Apache Kafka Examples

1) Apache Kafka example with Java Producer & Consumer Tutorial – Part 2

Apache Kafka Interview Q&As

1. Apache Kafka Interview Q&As


300+ Java Interview FAQs

Tutorials on Java & Big Data