0Pricing
Advanced Spring Boot 4: Event-Driven Architecture (Kafka) · บทเรียน

ผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์

ตอกย้ำความสำคัญของการออกแบบผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์ เพื่อให้สถานะยังคงสอดคล้องกันแม้ต้องประมวลผลข้อความซ้ำ

ผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์ เป็นบทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Advanced Spring Boot 4: Event-Driven Architecture (Kafka) มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What is Idempotence?

Imagine pressing a light switch. If you press it once, the light turns on. If you press it again, the light stays on – it doesn't get 'more on'. This is idempotence!

An operation is idempotent if performing it multiple times produces the same result as performing it once. It's about the final state, not how many times you tried to get there.

Why Idempotence in Messaging?

In distributed systems like those using Kafka, messages can sometimes be delivered more than once. This can happen due to network issues, consumer crashes, or rebalances.

If your application isn't designed to handle these duplicates, reprocessing the same message multiple times could lead to incorrect data or undesirable side effects.

Kafka's Idempotent Producers

Good news! Kafka provides built-in support for idempotent producers. This means when you send a message, Kafka guarantees that it will be written to the topic log exactly once, even if the producer retries sending it due to transient failures.

This prevents duplicate messages from being stored in Kafka itself.

How Kafka Idempotence Works

Kafka achieves producer idempotence by assigning a unique Producer ID (PID) to each producer session and a monotonically increasing sequence number to each message batch sent by that producer.

Kafka brokers use these IDs and sequence numbers to detect and discard any duplicate message batches before they are written to the log.

Enabling Idempotent Producers

In Spring Boot, enabling an idempotent Kafka producer is straightforward. You just need to set a specific property in your application.properties or application.yml.

  • spring.kafka.producer.properties.enable.idempotence=true

Setting this property also implicitly configures other necessary producer settings, such as acks=all and retries.

Idempotent Producer Example

Try running this simple Spring Boot application. It sends a message to a Kafka topic with idempotence enabled. Notice the configuration comments.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import java.util.UUID;

@SpringBootApplication
public class IdempotentProducerApp {

  public static void main(String[] args) {
    SpringApplication.run(IdempotentProducerApp.class, args);
  }

  @Bean
  public CommandLineRunner runner(
    KafkaTemplate<String, String> kafkaTemplate) {
    return args -> {
      String messageKey = UUID.randomUUID().toString();
      String messageValue = "Hello from Idempotent Producer!";
      System.out.println("Sending message with key: " 
                         + messageKey);
      kafkaTemplate.send("my-idempotent-topic", 
                         messageKey, messageValue)
        .addCallback(
          result -> System.out.println(
            "Message sent successfully!"),
          ex -> System.err.println(
            "Failed to send: " + ex.getMessage())
        );
    };
  }
}
// Add to application.properties:
// spring.kafka.producer.bootstrap-servers=localhost:9092
// spring.kafka.producer.key-serializer=
//   org.apache.kafka.common.serialization.StringSerializer
// spring.kafka.producer.value-serializer=
//   org.apache.kafka.common.serialization.StringSerializer
// spring.kafka.producer.properties.enable.idempotence=true

Idempotent Consumers

While Kafka helps producers avoid sending duplicates to the log, it doesn't guarantee that consumers will process messages exactly once. Consumers might read the same message multiple times.

Therefore, idempotent consumer logic is crucial. This means your application code must ensure that processing a message multiple times has no unintended side effects on your system's state.

Strategies for Idempotent Consumers

Here are common approaches to make your consumers idempotent:

  • Unique ID Tracking: Store a unique identifier (like Kafka's topic-partition-offset or a business ID from the message) in a persistent store. Check this store before processing.
  • State Comparison: Before applying an update, compare the incoming message's data with the current state in your system. Only apply if the state needs changing.
  • Business Idempotence: Design your business operations to be naturally idempotent. For example, 'set user status to X' is idempotent, 'increment user balance by Y' is not.

Consumer Idempotence Example

This Spring Boot example demonstrates a basic idempotent consumer using a set to track processed records. In a real application, this would be a persistent store like a database or Redis.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import java.util.HashSet;
import java.util.Set;

@SpringBootApplication
public class IdempotentConsumerApp {

  public static void main(String[] args) {
    SpringApplication.run(IdempotentConsumerApp.class, args);
  }

  @Component
  public static class MyKafkaListener {
    // In a real app, this would be a persistent store (DB, Redis)
    private final Set<String> processedRecordIds = new HashSet<>();

    @KafkaListener(topics = "my-idempotent-topic", 
                   groupId = "idempotent-group")
    public void listen(ConsumerRecord<String, String> record) {
      // Unique ID for the record (topic-partition-offset)
      String recordId = record.topic() + "-" + record.partition()
                        + "-" + record.offset();

      if (processedRecordIds.contains(recordId)) {
        System.out.println("Duplicate record received (ID: " 
                           + recordId + "). Skipping processing.");
        return;
      }

      // Simulate processing the message
      System.out.println("Processing record ID: " + recordId 
                         + ", Key: " + record.key() 
                         + ", Value: " + record.value());
      // Add to processed set AFTER successful processing
      processedRecordIds.add(recordId);

      // In a real scenario, processing might involve DB updates
      // and 'add' would happen as part of a transaction.
    }
  }
}
// Add to application.properties:
// spring.kafka.consumer.bootstrap-servers=localhost:9092
// spring.kafka.consumer.key-deserializer=
//   org.apache.kafka.common.serialization.StringDeserializer
// spring.kafka.consumer.value-deserializer=
//   org.apache.kafka.common.serialization.StringDeserializer
// spring.kafka.consumer.group-id=idempotent-group
// spring.kafka.consumer.auto-offset-reset=earliest

Quick Check: Idempotence

Test your understanding of idempotent operations in messaging.

Recap & Next Steps

Great job! In this lesson, you've learned about the vital concept of idempotence in event-driven systems.

  • You understand why idempotence is critical for maintaining consistent state when messages might be reprocessed.
  • You saw how Kafka's built-in idempotent producers prevent duplicate messages from entering the topic.
  • You explored strategies for building idempotent consumers, ensuring your application handles duplicate messages gracefully.

Mastering idempotence is a key step towards building robust and reliable Kafka applications!

คำถามที่พบบ่อย

บทเรียน “ผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Advanced Spring Boot 4: Event-Driven Architecture (Kafka) มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์”

ตอกย้ำความสำคัญของการออกแบบผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์ เพื่อให้สถานะยังคงสอดคล้องกันแม้ต้องประมวลผลข้อความซ้ำ คุณปฏิบัติ Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “ผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) นี้ได้ไหม

ได้ บทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เคล็ดลับการปรับประสิทธิภาพ Kafka
  2. ผู้ผลิตและผู้ใช้แบบไอดิมโพเทนต์
  3. การนำแอป Spring Boot Kafka ขึ้นคลาวด์
  4. การวางแผนความจุ: พาร์ทิชันและการจำลองข้อมูล
← กลับไปที่ Advanced Spring Boot 4: Event-Driven Architecture (Kafka)