Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.
  • Labs icon Lab
  • A Cloud Guru
Google Cloud Platform icon
Labs

Building a Kafka Consumer in Java

Kafka consumers provide the ability to process data that is stored in Kafka topics. Since you can write consumer code using the Consumer API, it is possible to build consumers that can do practically anything with your Kafka data. In this lab, you will have the opportunity to build a simple consumer that reads from a Kafka topic and writes data to a file on the disk. This lab will give you some hands-on experience with Kafka consumers. Hopefully, it will also spark your imagination about other tasks you might be able to accomplish with Kafka consumers!

Google Cloud Platform icon
Labs

Path Info

Level
Clock icon Intermediate
Duration
Clock icon 45m
Published
Clock icon Oct 18, 2019

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    Clone the Starter Project and Run It to Make Sure Everything Is Working

    1. Clone the starter project into the home directory:

      cd ~/
      git clone https://github.com/linuxacademy/content-ccdak-kafka-consumer-lab.git
      
    2. Run the code to ensure it works before modifying it:

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

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

  2. Challenge

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

    1. Edit the main class:
    vi src/main/java/com/linuxacademy/ccdak/consumer/Main.java
    
    1. Implement the consumer according to the provided specification:
    package com.linuxacademy.ccdak.consumer;
    
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.time.Duration;
    import java.util.Arrays;
    import java.util.Properties;
    import org.apache.kafka.clients.consumer.ConsumerRecord;
    import org.apache.kafka.clients.consumer.ConsumerRecords;
    import org.apache.kafka.clients.consumer.KafkaConsumer;
    
    public class Main {
    
        public static void main(String[] args) {
            Properties props = new Properties();
            props.setProperty("bootstrap.servers", "localhost:9092");
            props.setProperty("group.id", "group1");
            props.setProperty("enable.auto.commit", "true");
            props.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
            props.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
            KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
            consumer.subscribe(Arrays.asList("inventory_purchases"));
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter("/home/cloud_user/output/output.dat", true));
                while (true) {
                    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
                    for (ConsumerRecord<String, String> record : records) {
                        String recordString = "key=" + record.key() + ", value=" + record.value() + ", topic=" + record.topic() + ", partition=" + record.partition() + ", offset=" + record.offset();
                        System.out.println(recordString);
                        writer.write(recordString + "\n");
                    }
                    consumer.commitSync();
                    writer.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
    }
    
    1. Execute the program:
    ./gradlew run
    
    1. Verify that data is appearing in the output file:
    cat /home/cloud_user/output/output.dat
    

The Cloud Content team comprises subject matter experts hyper focused on services offered by the leading cloud vendors (AWS, GCP, and Azure), as well as cloud-related technologies such as Linux and DevOps. The team is thrilled to share their knowledge to help you build modern tech solutions from the ground up, secure and optimize your environments, and so much more!

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.

Start learning by doing today

View Plans