📖 Scenario: You are building a simple Java program that sends messages to a Kafka topic. Kafka is like a post office where your program can send letters (messages) to a specific mailbox (topic).In this project, you will create a Java Kafka producer client that sends messages to a topic named test-topic.
🎯 Goal: Build a Java Kafka producer client that sends three messages to the test-topic Kafka topic.
📋 What You'll Learn
Create a Java Properties object with Kafka producer configuration
Create a Kafka Producer<String, String> object
Send three messages with keys and values to the test-topic
Close the producer after sending messages
💡 Why This Matters
🌍 Real World
Kafka producers are used in real applications to send data streams like logs, user activity, or sensor data to Kafka topics for processing.
💼 Career
Understanding how to build Kafka producer clients in Java is essential for backend developers working with real-time data pipelines and event-driven architectures.
Progress0 / 4 steps
1
Create Kafka producer configuration
Create a Properties object called props and set these exact properties: bootstrap.servers to "localhost:9092", key.serializer to "org.apache.kafka.common.serialization.StringSerializer", and value.serializer to "org.apache.kafka.common.serialization.StringSerializer".
Kafka
Hint
Use props.put(key, value) to set each configuration property.
2
Create Kafka producer client
Create a Kafka Producer<String, String> object called producer using the props configuration.
Kafka
Hint
Use new KafkaProducer<>(props) to create the producer.
3
Send messages to Kafka topic
Use the producer.send() method to send these three messages to the test-topic topic: 1. Key: "key1", Value: "Hello Kafka 1" 2. Key: "key2", Value: "Hello Kafka 2" 3. Key: "key3", Value: "Hello Kafka 3" Use new ProducerRecord<>(topic, key, value) to create each message.
Kafka
Hint
Call producer.send() three times with the correct ProducerRecord arguments.
4
Close the Kafka producer and print confirmation
Close the producer using producer.close(). Then print exactly "Messages sent successfully" using System.out.println().
Kafka
Hint
Call producer.close() to release resources. Use System.out.println("Messages sent successfully") to print the confirmation.
Practice
(1/5)
1. What is the primary role of a Java producer client in Kafka?
easy
A. To send messages to Kafka topics
B. To consume messages from Kafka topics
C. To manage Kafka brokers
D. To monitor Kafka cluster health
Solution
Step 1: Understand Kafka client roles
Kafka has producers that send messages and consumers that receive messages.
Step 2: Identify the producer's function
A Java producer client specifically sends messages to Kafka topics.