Create Kafka Producer In Java

Write Kafka Messages in Java

In the previous topic, we have covered about how to setup kafka cluster on windows and create kafka topic. Please check the previous topic of Create Kafka Cluster , Kafka Consumer , Kafka Producer , Kafka Topics to understand the kafka setup, kafka broker and kafka topic creation so that you can easily create a Java program for the Kafka Producer.

In this article you will learn about how to write and publish kafka messages in Java. You can see the below example of Java program to write and publish Kafka messages in Java.

  1. After completed the kafka setup and creation of kafka topic, the next part is to create a producer to publish events/messages.
  2. Need to add below dependency to create a kafka producer in Java.
    <dependency>
        <groupId> org.apache.kafka </groupId>
        <artifactId> kafka-clients </artifactId>
        <version> 0.9.0.0 </version>
    </dependency>
  3. Create Topic
    import org.apache.kafka.clients.producer.KafkaProducer;
    import org.apache.kafka.clients.producer.ProducerRecord;
    import java.util.Properties;
    import org.apache.kafka.clients.consumer.*;
    import org.apache.kafka.common.serialization.StringDeserializer;
        
    public class KafkaProducerExample {
      static String TOPIC_NAME= "first-topic";
      public static void main(String args[]){
        try {
          Properties p = new Properties();
          p.setProperty( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092" );
          p.setProperty( ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName() );
          p.setProperty( ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName() );
    
          KafkaProducer<String, String> producer = new KafkaProducer<>(p);
    
          producer.send(new ProducerRecord<>(TOPIC_NAME, "I am Good!"));
          producer.send(new ProducerRecord<>(TOPIC_NAME, "What about You?"));
          producer.send(new ProducerRecord<>(TOPIC_NAME, "Hope you are also well?"));
    
          producer.flush();
          producer.close();
        }catch(Exception e){
            e.printStackTrace();
        }
      }
    }
  4. Check the messages are published or not in Kafka Yopic.
    Go to the bin directory on command prompt and write below comands.
    kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic first-topic --from-beginning

    Kafka check messages on command prompt

In the next topic, you will understand about how to read kafka message in java. See the details of Read Kafka Messages In Java