Kafka로 메시지 생성
Kafka 토픽으로 데이터를 효율적이고 안정적으로 전송하는 애플리케이션을 작성하는 방법을 살펴봅니다.
Kafka로 메시지 생성은(는) CoddyKit의 무료 Apache Kafka & Stream Processing Fundamentals 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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.serializerandvalue.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.msandbatch.sizefor 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.serversand serializers. - Messages are wrapped in
ProducerRecordobjects. - You can send messages synchronously (blocking) or asynchronously (non-blocking).
- Callbacks are used to handle asynchronous send results.
- The
ackssetting controls message durability.
Next, we'll dive into how applications read these messages using Kafka Consumers!
자주 묻는 질문
“Kafka로 메시지 생성” 강의는 무료인가요?
네 — “Kafka로 메시지 생성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Apache Kafka & Stream Processing Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Apache Kafka & Stream Processing Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“Kafka로 메시지 생성”에서 뭘 배우나요?
Kafka 토픽으로 데이터를 효율적이고 안정적으로 전송하는 애플리케이션을 작성하는 방법을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Apache Kafka & Stream Processing Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Apache Kafka & Stream Processing Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Apache Kafka & Stream Processing Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Kafka로 메시지 생성” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Apache Kafka & Stream Processing Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Apache Kafka & Stream Processing Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Kafka로 메시지 생성
- Kafka에서 메시지 소비
- 파티션 및 오프셋 이해
- 메시지 키와 파티셔닝 전략