Kafka Producer Examples Using Java: Apache Kafka is an open-source stream-processing software platform developed by LinkedIn and donated to the Apache Software Foundation, written in Scala and Java.

In this tutorial, we will see how to create Kafka producer examples using Java

  • Create a Simple Maven Project
  • Add below dependency to your POM
  • Create the Class with name SimpleProducer
  • Below is the code for creating the Producer in Kafka
import java.util.Properties;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

public class SimpleProducer {

	public static void main(String[] args) throws Exception {

		// Use the Topic already created in your kafka server
		String topicName = "testTopic";

		// create instance for properties to access producer configs
		Properties props = new Properties();

		// Assign kafka server Ip addresses
		props.put("bootstrap.servers", "localhost:9092");

		// Set acknowledgements for producer requests.
		props.put("acks", "all");

		// If the request fails, the producer can automatically retry,
		props.put("retries", 0);

		// Specify buffer size in config
		props.put("batch.size", 16384);

		// Reduce the no of requests less than 0
		props.put("linger.ms", 1);

		// The buffer.memory controls the total amount of memory available to
		// the producer for buffering.
		props.put("buffer.memory", 33554432);

		props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");

		props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

		Producer&lt;String, String&gt; producer = new KafkaProducer&lt;String, String&gt;(props);

		producer.send(new ProducerRecord&lt;String, String&gt;(topicName, Integer.toString(1),
		System.out.println("Message sent successfully");

Note :

  • Change the Topic name which already exists in your Kafka servers 
  • Change the Kafka Server Server IP address 

After running the SimplePrducer class as java application to insert record to your Kafka server

after running you can see the records using tool http://www.kafkatool.com/download.html

Download the tool and connect to the Kafka server and open the topic name and partition to see the inserted records like below

If you didn’t find any records Use the Play button to refresh the data


Thank You

Also Read: Kafka Consumer Examples Using Java

Kafka Producer Examples Using Java

Leave a Reply

Your email address will not be published. Required fields are marked *