Write a simple Java program to create a Kafka
producer and Produce messages to a topic.
Pre-requisites for Kafka Programming with Java
1. Installing Kafka (including the part about installing the Java 11 JDK)
2. Preferred: install IntelliJ Community Edition
Kafka Programming Activities
In this section, we'll use Java programming language to programmatically replicate
what we were able to achieve with Kafka CLI.
Implementation:
Open the project in IntelliJ. Create a new java class under [Link] folder with the name producer.
Start with public static void main(String[] args)
Producer to produce message to a give topic
Following are the steps for writing the producer code
1. Create Properties object for Producer: Following the important properties of the producer we need to set
before we create theproducer
1. Bootstrap server details
2. Value serializer
3. key serializer
2. Create the Producer:
3. Create the producer Record: Which is record which will be sent to the kafka server
4. Send data: Asynchronously
5. Flush and close the producer
Java Code:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Producer {
public static void main(String[] args) {
//Create Properties object for Producer
Properties prop = new Properties();
[Link](ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"[Link]:9092");
[Link](ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, [Link]());
[Link](ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,[Link]());
// Create the Producer
final KafkaProducer<String,String> producer=new KafkaProducer<String,String>(prop);
// Create the producer Record
ProducerRecord<String, String> record = new ProducerRecord<>("MGITCSD","Key1","hello this is producer");
// Send data: Asynchronously
[Link](record);
// Flush and close the producer
[Link]();
[Link]();
}
}
Consumer execution:
1. Open a consumer console to read messages from the topic:
Bin\windows\[Link] --topic MGITCSD --from-beginning --
bootstrap-server localhost:9092
To run the Program:
1. Start Zooker
2. Start the kafka
3. Execute the javaProducer code
4. Execute the JavaConsumer Code