How to build your first Apache KafkaProducer application

Question:

How do I get started in building my first Kafka producer application?

Edit this page

Example use case:

You'd like to integrate an Apache KafkaProducer in your event-driven application, but you're not sure where to start. In this tutorial you'll build a small application writing records to Kafka with a KafkaProducer. You can use the code in this tutorial as an example of how to use an Apache Kafka producer


TweetShare your tutorial progress

Hands-on code example:

New to Confluent Cloud? Sign up and then run this tutorial.

Run it

1
Provision your Kafka cluster

The quickest way to get started with Apache Kafka is on Confluent Cloud, which provides it as a fully managed service. First, sign up for Confluent Cloud.

  1. After you log in to Confluent Cloud, click on Add cloud environment and name the environment learn-kafka. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.

  2. From the Billing & payment section in the Menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details).

  3. Click on LEARN and follow the instructions to launch a Kafka cluster and to enable Schema Registry.

Confluent Cloud

2
Initialize the project

Make a local directory anywhere you’d like for this project:

mkdir kafka-producer-application && cd kafka-producer-application

Next, create a directory for configuration data:

mkdir configuration

3
Write the cluster information into a local file

From the Confluent Cloud Console, navigate to your Kafka cluster. From the Clients view, get the connection information customized to your cluster (select Java).

Create new credentials for your Kafka cluster and Schema Registry, and then Confluent Cloud will show a configuration similar to below with your new credentials automatically populated (make sure show API keys is checked). Copy and paste it into a configuration/ccloud.properties file on your machine.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule   required username='{{ CLUSTER_API_KEY }}'   password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips

# Best practice for Kafka producer to prevent data loss
acks=all

# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url={{ SR_URL }}
basic.auth.credentials.source=USER_INFO
basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}
Do not directly copy and paste the above configuration. You must copy it from the Confluent Cloud Console so that it includes your Confluent Cloud information and credentials.

4
Download and setup the Confluent Cloud CLI

This tutorial has some steps for Kafka topic management and/or reading from or writing to Kafka topics, for which you can use the Confluent Cloud Console or install the Confluent Cloud CLI. Instructions for installing Confluent Cloud CLI and configuring it to your Confluent Cloud environment is available from within the Confluent Cloud Console: navigate to your Kafka cluster, click on the CLI and tools section, and run through the steps in the CCloud CLI tab.

5
Create a topic

In this step we’re going to create a topic for use during this tutorial. Use the following command to create the topic:

ccloud kafka topic create output-topic --partitions 1

6
Configure the project

Create the following Gradle build file for the project, named build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "com.commercehub.gradle.plugin:gradle-avro-plugin:0.22.0"
        classpath "com.github.jengelman.gradle.plugins:shadow:4.0.2"
    }
}

plugins {
    id "java"
    id "com.google.cloud.tools.jib" version "3.1.1"
    id "idea"
    id "eclipse"
}

sourceCompatibility = "1.8"
targetCompatibility = "1.8"
version = "0.0.1"

repositories {
    mavenCentral()

    maven {
        url "https://packages.confluent.io/maven"
    }
}

apply plugin: "com.commercehub.gradle.plugin.avro"
apply plugin: "com.github.johnrengelman.shadow"

dependencies {
    implementation "org.apache.avro:avro:1.10.2"
    implementation "org.slf4j:slf4j-simple:1.7.30"
    implementation "org.apache.kafka:kafka-streams:2.8.1"
    implementation "io.confluent:kafka-streams-avro-serde:6.2.1"
    testImplementation "org.apache.kafka:kafka-streams-test-utils:2.8.1"
    testImplementation "junit:junit:4.13.2"
    testImplementation 'org.hamcrest:hamcrest:2.2'
}

test {
    testLogging {
        outputs.upToDateWhen { false }
        showStandardStreams = true
        exceptionFormat = "full"
    }
}

jar {
  manifest {
    attributes(
      "Class-Path": configurations.compileClasspath.collect { it.getName() }.join(" "),
      "Main-Class": "io.confluent.developer.KafkaProducerApplication"
    )
  }
}

shadowJar {
    archiveBaseName = "kafka-producer-application-standalone"
    archiveClassifier = ''
}

Run the following command to obtain the Gradle wrapper:

gradle wrapper

7
Add application and producer properties

Then create a development file at configuration/dev.properties:

key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
acks=all

#Properties below this line are specific to code in this application
input.topic.name=input-topic
output.topic.name=output-topic

Let’s do a quick walkthrough of some of the producer properties.

key.serializer - The serializer the KafkaProducer will use to serialize the key.

value.serializer - The serializer the KafkaProducer will use to serialize the value.

acks - The KafkaProducer uses the acks configuration to tell the lead broker how many acknowledgments to wait for to consider a produce request complete. Acceptable values for acks are: 0, 1 (the default), -1, or all. Setting acks to -1 is the same as setting it to all.

  • acks=0: "fire and forget", once the producer sends the record batch it is considered successful

  • acks=1: leader broker added the records to its local log but didn’t wait for any acknowledgment from the followers

  • acks=all: highest data durability guarantee, the leader broker persisted the record to its log and received acknowledgment of replication from all in-sync replicas. When using acks=all, it’s strongly recommended to update min.insync.replicas as well.

This is only a small sub-set of producer configuration parameters. The full list of producer configuration parameters can be found in the Apache Kafka documentation.

8
Update the properties file with Confluent Cloud information

Using the command below, append the contents of configuration/ccloud.properties (with your Confluent Cloud configuration) to configuration/dev.properties (with the application properties).

cat configuration/ccloud.properties >> configuration/dev.properties

9
Create the KafkaProducer application

Create a directory for the Java files in this project:

mkdir -p src/main/java/io/confluent/developer

Before you create your application file, let’s look at some of the key points of this program:

KafkaProducerApplication constructor
public class KafkaProducerApplication {

  private final Producer<String, String> producer;
  final String outTopic;

  public KafkaProducerApplication(final Producer<String, String> producer,  (1)
                                  final String topic) {                     (2)
    this.producer = producer;
    outTopic = topic;
  }
1 Passing in the Producer instance as a constructor parameter.
2 The topic to write records to

In this tutorial you’ll inject the dependencies in the KafkaProducerApplication.main() method. Having this thin wrapper class around a Producer is not required, but it does help with making our code easier to test. We’ll go into more details in the testing section of the tutorial.

(In practice you may want to use a dependency injection framework library, such as the Spring Framework).

Next let’s take a look at the KafkaProducerApplication.produce method

KafkaProducerApplication.produce
public Future<RecordMetadata> produce(final String message) {
    final String[] parts = message.split("-");  (1)
    final String key, value;
    if (parts.length > 1) {
      key = parts[0];
      value = parts[1];
    } else {
      key = "NO-KEY";
      value = parts[0];
    }
    final ProducerRecord<String, String> producerRecord = new ProducerRecord<>(outTopic, key, value);  (2)
    return producer.send(producerRecord);                 (3)
  }
1 Process the String for sending message
2 Create the ProducerRecord
3 Send the record to the broker

The KafkaProducerApplication.produce method does some processing on a String, and then sends the ProducerRecord. While this code is a trivial example, it’s enough to show the example of using a KafkaProducer. Notice that KafkaProducer.send returns a Future with a type of RecordMetadata.

The KafkaProducer.send method is asynchronous and returns as soon as the provided record is placed in the buffer of records to be sent to the broker. Once the broker acknowledges that the record has been appended to its log, the broker completes the produce request, which the application receives as RecordMetadata—information about the committed message. This tutorial prints the timestamp and offset for each record sent using the RecordMetadata object. Note that calling Future.get() for any record will block until the produce request completes.

Now go ahead and create the following file at src/main/java/io/confluent/developer/KafkaProducerApplication.java.

package io.confluent.developer;


import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

public class KafkaProducerApplication {

    private final Producer<String, String> producer;
    final String outTopic;

    public KafkaProducerApplication(final Producer<String, String> producer,
                                    final String topic) {
        this.producer = producer;
        outTopic = topic;
    }

    public Future<RecordMetadata> produce(final String message) {
        final String[] parts = message.split("-");
        final String key, value;
        if (parts.length > 1) {
            key = parts[0];
            value = parts[1];
        } else {
            key = null;
            value = parts[0];
        }
        final ProducerRecord<String, String> producerRecord = new ProducerRecord<>(outTopic, key, value);
        return producer.send(producerRecord);
    }

    public void shutdown() {
        producer.close();
    }

    public static Properties loadProperties(String fileName) throws IOException {
        final Properties envProps = new Properties();
        final FileInputStream input = new FileInputStream(fileName);
        envProps.load(input);
        input.close();

        return envProps;
    }

    public void printMetadata(final Collection<Future<RecordMetadata>> metadata,
                              final String fileName) {
        System.out.println("Offsets and timestamps committed in batch from " + fileName);
        metadata.forEach(m -> {
            try {
                final RecordMetadata recordMetadata = m.get();
                System.out.println("Record written to offset " + recordMetadata.offset() + " timestamp " + recordMetadata.timestamp());
            } catch (InterruptedException | ExecutionException e) {
                if (e instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            throw new IllegalArgumentException(
                    "This program takes two arguments: the path to an environment configuration file and" +
                            "the path to the file with records to send");
        }

        final Properties props = KafkaProducerApplication.loadProperties(args[0]);
        final String topic = props.getProperty("output.topic.name");
        final Producer<String, String> producer = new KafkaProducer<>(props);
        final KafkaProducerApplication producerApp = new KafkaProducerApplication(producer, topic);

        String filePath = args[1];
        try {
            List<String> linesToProduce = Files.readAllLines(Paths.get(filePath));
            List<Future<RecordMetadata>> metadata = linesToProduce.stream()
                    .filter(l -> !l.trim().isEmpty())
                    .map(producerApp::produce)
                    .collect(Collectors.toList());
            producerApp.printMetadata(metadata, filePath);

        } catch (IOException e) {
            System.err.printf("Error reading file %s due to %s %n", filePath, e);
        }
        finally {
            producerApp.shutdown();
        }
    }
}

10
Create data to produce to Kafka

Create the following file input.txt in the base directory of the tutorial. The numbers before the - will be the key and the part after will be the value.

1-value
2-words
3-All Streams
4-Lead to
5-Kafka
6-Go to
7-Kafka Summit
8-How can
9-a 10 ounce
10-bird carry a
11-5lb coconut

11
Compile and run the KafkaProducer application

In your terminal, run:

./gradlew shadowJar

Now that you have an uberjar for the KafkaProducerApplication, you can launch it locally.

java -jar build/libs/kafka-producer-application-standalone-0.0.1.jar configuration/dev.properties input.txt

After you run the previous command, the application will process the file and you should something like this on the console:

Offsets and timestamps committed in batch from input.txt
Record written to offset 0 timestamp 1597352120029
Record written to offset 1 timestamp 1597352120037
Record written to offset 2 timestamp 1597352120037
Record written to offset 3 timestamp 1597352120037
Record written to offset 4 timestamp 1597352120037
Record written to offset 5 timestamp 1597352120037
Record written to offset 6 timestamp 1597352120037
Record written to offset 7 timestamp 1597352120037
Record written to offset 8 timestamp 1597352120037
Record written to offset 9 timestamp 1597352120037
Record written to offset 10 timestamp 1597352120038

Now you can experiment some by creating your own file in base directory and re-run the above command and substitute your file name for input.txt

Remember any data before the - is the key and data after is the value.

12
Confirm records sent by consuming from topic

Now run a console consumer that will read topics from the output topic to confirm your application published the expected records.

ccloud kafka topic consume output-topic -b --print-key --delimiter " : "

The output from the consumer can vary if you added any of your own records, but it should look something like this:

1 : value
2 : words
3 : All Streams
4 : Lead to
5 : Kafka
6 : Go to
7 : Kafka Summit
8 : How can
9 : a 10 ounce
10 : bird carry a
11 : 5lb coconut

Now close the consumer with a CTRL+C then the broker shell with a CTRL+D

13
Teardown Confluent Cloud resources

You may try another Kafka tutorial, but if you don’t plan on doing other tutorials, use the Confluent Cloud Console or CLI to destroy all the resources you created. Verify they are destroyed to avoid unexpected charges.

Test it

1
Create a test configuration file

First, create a test file at configuration/test.properties:

key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
acks=all


#Properties below this line are specific to code in this application
input.topic.name=input-topic
output.topic.name=output-topic

2
Write a unit test

Create a directory for the tests to live in:

mkdir -p src/test/java/io/confluent/developer

Next we will see why the thin wrapper class around the KafkaProducer makes testing easier. The KafkaProducerApplication accepts an instance of the Producer interface. The use of the interface allows us to inject any concrete type we want, including a Mock Producer for testing.

We use a MockProducer because you only want to test your own code. So you really only need to test that the producer receives the expected records and in the expected format. Plus since there is no broker, the tests run very fast, which becomes an important factor as the number of tests increase.

There is only one method in KafkaProducerApplicationTest annotated with @Test, and that is testProduce(). Before you create the test, let’s go over a few of the key points of the test

final List<String> records = Arrays.asList("foo#bar", "bar#foo", "baz#bar", "great-weather");

records.forEach(producerApp::produce); (1)

final List<KeyValue<String, String>> expectedList = Arrays.asList(KeyValue.pair("foo", "bar"),
            KeyValue.pair("bar", "foo"),
            KeyValue.pair("baz", "bar"),
            KeyValue.pair("NO-KEY","great:weather")); (2)
final List<KeyValue<String, String>> actualList = mockProducer.history().stream().map(this::toKeyValue).collect(Collectors.toList()); (3)
1 Call the produce method
2 Build the expected list of records the producer should receive
3 Use the MockProducer.history() method to get the records sent to the producer so the test can assert the expected records match the actual ones sent

Now create the following file at src/test/java/io/confluent/developer/KafkaProducerApplicationTest.java.

package io.confluent.developer;


import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.streams.KeyValue;
import org.junit.Test;


public class KafkaProducerApplicationTest {

    private final static String TEST_CONFIG_FILE = "configuration/test.properties";

    @Test
    public void testProduce() throws IOException {
        final StringSerializer stringSerializer = new StringSerializer();
        final MockProducer<String, String> mockProducer = new MockProducer<>(true, stringSerializer, stringSerializer);
        final Properties props = KafkaProducerApplication.loadProperties(TEST_CONFIG_FILE);
        final String topic = props.getProperty("output.topic.name");
        final KafkaProducerApplication producerApp = new KafkaProducerApplication(mockProducer, topic);
        final List<String> records = Arrays.asList("foo-bar", "bar-foo", "baz-bar", "great:weather");

        records.forEach(producerApp::produce);

        final List<KeyValue<String, String>> expectedList = Arrays.asList(KeyValue.pair("foo", "bar"),
            KeyValue.pair("bar", "foo"),
            KeyValue.pair("baz", "bar"),
            KeyValue.pair(null,"great:weather"));

        final List<KeyValue<String, String>> actualList = mockProducer.history().stream().map(this::toKeyValue).collect(Collectors.toList());

        assertThat(actualList, equalTo(expectedList));
        producerApp.shutdown();
    }


    private KeyValue<String, String> toKeyValue(final ProducerRecord<String, String> producerRecord) {
        return KeyValue.pair(producerRecord.key(), producerRecord.value());
    }
}

3
Invoke the tests

Now run the test, which is as simple as:

./gradlew test

Take it to production

1
Create a production configuration file

First, create a new configuration file at configuration/prod.properties with the following content. Be sure to fill in the addresses of your production hosts and change any other parameters that make sense for your setup.

bootstrap.servers=<FILL ME IN>

key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
acks=all


#Properties below this line are specific to code in this application
input.topic.name=<FILL ME IN>
output.topic.name=<FILL ME IN>

2
Build a Docker image

In your terminal, execute the following to invoke the Jib plugin to build an image:

gradle jibDockerBuild --image=io.confluent.developer/kafka-producer-application-join:0.0.1

3
Launch the container

Finally, launch the container using your preferred container orchestration service. If you want to run it locally, you can execute the following:

docker run -v $PWD/configuration/prod.properties:/config.properties io.confluent.developer/kafka-producer-application-join:0.0.1 config.properties