Apache Kafka & Stream Processing Fundamentals · Урок

Отправка сообщений в Kafka

Изучите, как создавать приложения, эффективно и надёжно отправляющие данные в топики Kafka.

Урок 1 из 412 шагов

«Отправка сообщений в Kafka» — бесплатный урок Apache Kafka & Stream Processing Fundamentals на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Apache Kafka & Stream Processing Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Apache Kafka & Stream Processing Fundamentals содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Meet the Kafka Producer

In this lesson, we'll learn how to send messages (also called records) to Kafka topics. This is the job of a Kafka Producer.

Think of a producer as an application or service that generates data. It then sends this data to a Kafka cluster, where it's stored in specific topics for other applications to read.

  • Producers generate data.
  • Topics organize data streams.
  • Brokers store the data.

Producer Client Basics

To send data, your application uses a Kafka Producer client library. This library handles all the complex interactions with the Kafka brokers.

It takes care of:

  • Finding the right Kafka broker.
  • Serializing your data into bytes.
  • Retrying failed send operations.
  • Balancing message distribution.

We'll use Java examples, but the concepts apply across languages.

Essential Producer Config

Before a producer can send messages, it needs some basic configuration. The two most important settings are:

  • bootstrap.servers: A comma-separated list of host/port pairs for Kafka brokers. The producer uses these to discover the full cluster.
  • key.serializer and value.serializer: Classes that convert your message's key and value objects into byte arrays, which is how Kafka stores data.

Without these, the producer won't know where to send messages or how to format them.

Producer Config Example

Here's how you might set up these properties in Java:

import java.util.Properties;

public class ProducerConfigDemo {
  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");

    System.out.println("Producer properties configured!");
    // In a real app, you'd create a KafkaProducer with these props
  }
}

Crafting Your Message: ProducerRecord

When you send data to Kafka, you don't just send a string. You send a ProducerRecord. This object encapsulates your message and its metadata.

A ProducerRecord requires:

  • The topic name where the message will be sent.
  • An optional key: Used for partitioning messages. Messages with the same key go to the same partition.
  • The value: The actual data you want to send.

Keys are important for ensuring ordering for related data within a topic.

Sending Messages (Blocking)

The simplest way to send a message is using the send() method. If you want to wait for the message to be acknowledged by Kafka, you can call .get() on the returned Future object.

This makes the send operation synchronous (blocking). It's easy to understand, but can be slow if you're sending many messages.

import org.apache.kafka.clients.producer.*;
import java.util.Properties;

public class SyncProducer {
  public static void main(String[] args) throws Exception {
    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");

    try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
      ProducerRecord<String, String> record = new ProducerRecord<>(
        "my-topic", "key1", "Hello Sync Kafka!");
      
      RecordMetadata metadata = producer.send(record).get(); // Blocks here
      System.out.println("Sent message: " + metadata.topic() + "-" + metadata.partition());
    }
  }
}

Sending Messages (Non-Blocking)

For better performance, Kafka producers are designed to send messages asynchronously. When you call send(), it adds the message to a buffer and returns immediately.

The actual sending happens in the background. This allows your application to continue processing without waiting for each message to be delivered.

import org.apache.kafka.clients.producer.*;
import java.util.Properties;

public class AsyncProducer {
  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");

    try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
      ProducerRecord<String, String> record = new ProducerRecord<>(
        "my-topic", "key2", "Hello Async Kafka!");
      
      producer.send(record); // Returns immediately
      System.out.println("Message queued for sending.");
      // In a real app, you'd send many messages here
    }
  }
}

Handling Send Results with Callbacks

Since send() is asynchronous, how do you know if a message was successfully sent or if an error occurred? You use a Callback.

The callback function is executed once Kafka acknowledges the message or if an error prevents it from being sent. This is crucial for error handling and logging.

import org.apache.kafka.clients.producer.*;
import java.util.Properties;

public class CallbackProducer {
  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");

    try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
      ProducerRecord<String, String> record = new ProducerRecord<>(
        "my-topic", "key3", "Hello Callback Kafka!");
      
      producer.send(record, new Callback() {
        @Override
        public void onCompletion(RecordMetadata metadata, Exception exception) {
          if (exception == null) {
            System.out.println("Message sent successfully to topic " + metadata.topic());
          } else {
            System.err.println("Error sending message: " + exception.getMessage());
          }
        }
      });
      // Must flush or close producer to ensure callback is triggered in short programs
      producer.flush(); 
    }
  }
}

Ensuring Delivery: Acks Configuration

Producer reliability is controlled by the acks configuration. This setting determines how many acknowledgments a producer needs from Kafka brokers before considering a message 'sent'.

  • acks=0: Producer sends and doesn't wait for any acknowledgment. Fastest, but lowest durability (messages might be lost).
  • acks=1: Producer waits for the leader broker to acknowledge receipt. Good balance of speed and durability.
  • acks=all (or -1): Producer waits for all in-sync replicas to acknowledge. Slowest, but highest durability (messages are very unlikely to be lost).

Producer Best Practices

To ensure your Kafka producers are efficient and robust:

  • Always close the producer: Call producer.close() when your application shuts down. This flushes any buffered messages and releases resources.
  • Batching: Kafka producers automatically batch messages for efficiency. You can tune linger.ms and batch.size for optimal throughput.
  • Error Handling: Implement robust error handling in your callbacks to deal with transient network issues or permanent errors.

Proper configuration and resource management are key to a healthy Kafka application.

Quick Check: Producers

Which producer configuration property specifies how many acknowledgments the producer needs from Kafka brokers before considering a message successfully sent?

Producer Summary

You've learned the fundamentals of producing messages to Kafka!

  • Producers send data to topics.
  • Key configurations include bootstrap.servers and serializers.
  • Messages are wrapped in ProducerRecord objects.
  • You can send messages synchronously (blocking) or asynchronously (non-blocking).
  • Callbacks are used to handle asynchronous send results.
  • The acks setting controls message durability.

Next, we'll dive into how applications read these messages using Kafka Consumers!

Можно начать бесплатно

Изучай Apache Kafka & Stream Processing Fundamentals с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Отправка сообщений в Kafka» бесплатный?

Да — полный текст урока «Отправка сообщений в Kafka» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Apache Kafka & Stream Processing Fundamentals, подпишись на CoddyKit PRO. Курс Apache Kafka & Stream Processing Fundamentals содержит 4 уроков всего.

Чему я научусь в уроке «Отправка сообщений в Kafka»?

Изучите, как создавать приложения, эффективно и надёжно отправляющие данные в топики Kafka. Ты практикуешь Apache Kafka & Stream Processing Fundamentals с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Apache Kafka & Stream Processing Fundamentals?

Предыдущий опыт не требуется. Apache Kafka & Stream Processing Fundamentals на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Отправка сообщений в Kafka»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Apache Kafka & Stream Processing Fundamentals?

Да. Каждый урок Apache Kafka & Stream Processing Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Отправка сообщений в Kafka
  2. Получение сообщений из Kafka
  3. Понимание разделов и смещений
  4. Ключи сообщений и стратегии распределения по разделам
← Назад к Apache Kafka & Stream Processing Fundamentals