Kafka Code Example Tutorial With Working Snippets

Apache Kafka, an open-source distributed event streaming platform, has become integral to real-time data pipelines and streams processing for numerous applications. Understanding how to code with Kafka is paramount for leveraging its potential. This comprehensive guide walks you through a critical Kafka code example, delving into its core concepts and execution in a simple, stepwise approach.

Kafka Producer API Internals
Kafka Producer API Internals

Kafka uses a publish-subscribe model, where producers send messages to topics, and consumers subscribe to these topics to receive those messages. Let's first establish a basic Kafka code example using the popular Kafka Java client library.

Alex Xu (@alexxubyte) on X
Alex Xu (@alexxubyte) on X

Setting up the Environment

The first step involves setting up the Kafka environment and initializing the producer and consumer. This includes creating a new Kafka instance, creating a topic, and setting up the necessary properties for the producer and consumer.

kafka
kafka

The following code snippet demonstrates how to set up a single-node Kafka cluster and create a Kafka producer and consumer:

```java 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"); Producer producer = new KafkaProducer<>(props); props.put("group.id", "test"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); Consumer consumer = new KafkaConsumer<>(props); ```

Creating and Using a Kafka Producer

the kafka at user diagram
the kafka at user diagram

The next step is creating and utilizing a Kafka producer. A producer is responsible for sending (publishing) messages to a Kafka topic. The following code creates a Kafka producer and sends a message to a topic:

```java producer.send(new ProducerRecord<>("my-topic", "my-key", "my-value")); ```

Creating and Using a Kafka Consumer

Following the creation of a producer, the next logical step is setting up a consumer to receive the messages sent by the producer. Consumers subscribe to topics and pull the messages from them, as illustrated in the following code:

Apache Kafka Infographic
Apache Kafka Infographic

```java consumer.subscribe(Collections.singletonList("my-topic")); while (true) { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { System.out.printf("Received message: Key = %s, Value = %s%n", record.key(), record.value()); } } ```

Note: The consumer in this example is an infinite loop polling the Kafka topic every 100 milliseconds. You can add a break condition or control the message loop as per your application requirements.

Handling Kafka Records

The messages producers send and consumers retrieve are Kafka records. Producers serialize their data into records, which are essentially key-value pairs with metadata like timestamps, headers, and offsets.

a diagram showing the architecture of a kafka architecture, with different types of products and
a diagram showing the architecture of a kafka architecture, with different types of products and

Managing Record Headers

Kafka records can hold a payload of key-value pairs and headers. The following code demonstrates how to add headers to a Kafka record:

an info sheet with the words apache kafka chatsheet
an info sheet with the words apache kafka chatsheet
the diagram shows how kafka works and what it is like to work with them
the diagram shows how kafka works and what it is like to work with them
Kafka intro
Kafka intro
the top 8 kafka use cases
the top 8 kafka use cases
Top 5 Kafka Use Cases
Top 5 Kafka Use Cases
the kafka on kubernets diagram shows how it is used to store products
the kafka on kubernets diagram shows how it is used to store products
the diagram shows how to use kafka for data processing and storage in an application
the diagram shows how to use kafka for data processing and storage in an application
the top 6 kafka use cases
the top 6 kafka use cases
(25) Feed | LinkedIn Cloud Computing Services, Charts And Graphs, Cloud Computing, Computer Science, Software Development, Software, Computer, Science, Engineering
(25) Feed | LinkedIn Cloud Computing Services, Charts And Graphs, Cloud Computing, Computer Science, Software Development, Software, Computer, Science, Engineering
a diagram showing the different types of cloud computing
a diagram showing the different types of cloud computing
Client Challenge
Client Challenge
Kafka Internals - Apache Kafka
Kafka Internals - Apache Kafka
Client Challenge
Client Challenge
the diagram shows how kafka is used to create an application for data storage
the diagram shows how kafka is used to create an application for data storage
Kafka vs RabbitMQ: Which Broker Do You Need? 🐇📦
Kafka vs RabbitMQ: Which Broker Do You Need? 🐇📦
Kafka Technical Overview
Kafka Technical Overview
Omkar Srivastava on LinkedIn: #devops #engineering #softwareengineer #kubernetes | 66 comments
Omkar Srivastava on LinkedIn: #devops #engineering #softwareengineer #kubernetes | 66 comments
Apache Kafka For Data Pipeline
Apache Kafka For Data Pipeline
Brij kishore Pandey on LinkedIn: RabbitMQ vs Kafka: Choosing the Right Message Broker for Your Architecture…
Brij kishore Pandey on LinkedIn: RabbitMQ vs Kafka: Choosing the Right Message Broker for Your Architecture…
a diagram showing how to use the kaka fast appliance for an application
a diagram showing how to use the kaka fast appliance for an application

```java RecordHeader header = new RecordHeader("header-key".getBytes(StandardCharsets.UTF_8), "header-value".getBytes(StandardCharsets.UTF_8)); producer.send(new ProducerRecord<>("my-topic", "my-key", "my-value", headers(header))); ```

To access these headers in a consumer, similar to the following:

```java for (Header header : records.header()) { System.out.printf("%s : %s%n", new String(header.key(), StandardCharsets.UTF_8), new String(header.value(), StandardCharsets.UTF_8)); } ```

Handling Record Timestamps

richectic software design be provided when writing the software. The goal of good software design is to allow the software to evolve strengths of Kafka is the ability to store and retrieve message timestamps. Useful when debugging or auditing, timestamps can be provided by Kafka automatically or by the producer.

Finally, don't forget to close your producer and consumer connections once done using `producer.close()` and `consumer.close()` respectively.

This Kafka code example merely scratches the surface of what's possible with Kafka. Explore further features such as partitioning, replication, message processing guarantees, and failure handling to fully leverage Kafka's capabilities. Happy coding!

Related Articles

Kafka Python Producer Consumer Example Simple Chatbot Code In Python Python Kivy Github Python Example Projects Github Python Kivy App Examples Opencv Sample Image Python Sample Without Replacement From List Sample Python Apps Two Sample T Test Python Code Playwright Python Sample Project