[Kafka Cookboook] Simple Producer

Now that we have completed a Quick Start, let’s see how to write a basic Java Producer for Kafka.

Kafka setup is up and running (including Zookeeper)

If you are using Maven, here are the needed dependencies


The producer is going to be simple, which would just be in a loop and send a message with a delay.
The purpose is just to write a simple producer and explore the API.

Here is the Code

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.HashMap;
import java.util.Map;

 * Simple Producer
public class KafkaMessageProducer {

  public static void main(String[] args) {
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    config.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    config.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    KafkaProducer<String, String> producer = new KafkaProducer<String, String>(config);

    int maxMessages = 1000;

    int count = 0;
    while(count < maxMessages) {
      producer.send(new ProducerRecord<String, String>("testTopic", "msg", "message --- #"+count++));
      System.out.println("Message send.."+count);


Let’s look at the code. The initial part deals with configuration options like Bootstrap host Address from where it would fetch further information. Key and Value Serializer are the options used to convert to binary form and vise-versa. Using the configuration, we instantiate a Kafka Producer. Sending the message is simple, we need to create a ProducerRecord with desired key and value and call send() on producer instance.

That’s it. The example sends 1000 messages, you can configure in the way you like.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.