Skip to main content

Building a Kafka Producer in Java

Hands-On Lab

 

Photo of Will Boyd

Will Boyd

DevOps Team Lead in Content

Length

00:45:00

Difficulty

Intermediate

Kafka producers allow you to write data to Kafka topics easily. Since you can build your own producers, you will be capable of developing logic to handle messages in ways that serve a variety of use cases. In this lab, you will have the opportunity to work with your own Kafka producer written in Java. You will solve a particular use case by building your producer logic — writing messages to multiple Kafka topics. This will give you some hands-on experience with building your own Kafka producers in Java.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Building a Kafka Producer in Java

Introduction

In this hands-on lab, we will have the opportunity to work with a Kafka producer written in Java. We will solve a particular use case by building producer logic — writing messages to multiple Kafka topics.

Solution

Begin by logging in to the lab servers using the credentials provided on the hands-on lab page:

  ssh cloud_user@PUBLIC_IP_ADDRESS

Clone the Starter Project and Run It to Verify That It Works

  1. Clone the starter project into the home directory:

    cd ~/
    git clone https://github.com/linuxacademy/content-ccdak-kafka-producer-lab.git
  2. View the creation of the content-ccdak-kafka-producer-lab directory:

    ls
  3. Run the code to ensure it works before modifying it:

    cd content-ccdak-kafka-producer-lab/
    ./gradlew run

    Note: We should see a Hello, world! message in the output.

Implement the Producer and Run It to Verify That It Works as Expected

  1. Edit the main class:

    vi src/main/java/com/linuxacademy/ccdak/producer/Main.java
  2. Implement the producer according to the provided specification:

    package com.linuxacademy.ccdak.producer;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Properties;
    import org.apache.kafka.clients.producer.KafkaProducer;
    import org.apache.kafka.clients.producer.Producer;
    import org.apache.kafka.clients.producer.ProducerRecord;
    
    public class Main {
    
      public static void main(String[] args) {
          Properties props = new Properties();
          props.put("bootstrap.servers", "localhost:9092");
          props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
          props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    
          props.put("acks", "all");
    
          Producer<String, String> producer = new KafkaProducer<>(props);
    
          try {
              File file = new File(Main.class.getClassLoader().getResource("sample_transaction_log.txt").getFile());
              BufferedReader br = new BufferedReader(new FileReader(file));
              String line;
              while ((line = br.readLine()) != null) {
                  String[] lineArray = line.split(":");
                  String key = lineArray[0];
                  String value = lineArray[1];
                  producer.send(new ProducerRecord<>("inventory_purchases", key, value));
                  if (key.equals("apples")) {
                      producer.send(new ProducerRecord<>("apple_purchases", key, value));
                  }
              }
              br.close();
          } catch (IOException e) {
              throw new RuntimeException(e);
          }
    
          producer.close();
      }
    
    }
  3. Save and exit.

  4. Execute the program:

    ./gradlew run

    Note: We should see a BUILD SUCCESSFUL message.

  5. Consume the records from the inventory_purchases topic and verify that we can see the new records created by the producer:

    kafka-console-consumer --bootstrap-server localhost:9092 --topic inventory_purchases --property print.key=true --from-beginning
  6. Consume the records from the apple_purchases topic to verify that we can see the new records created by the producer:

    kafka-console-consumer --bootstrap-server localhost:9092 --topic apple_purchases --property print.key=true --from-beginning

    Conclusion

    Congratulations — you've completed this hands-on lab!