0Pricing
RabbitMQ Messaging & Async Systems · บทเรียน

รูปแบบ Saga ด้วย RabbitMQ

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

รูปแบบ Saga ด้วย RabbitMQ เป็นบทเรียน RabbitMQ Messaging & Async Systems ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน RabbitMQ Messaging & Async Systems และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน

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

Distributed Transactions Unveiled

In microservices, a single business operation often spans multiple services. For example, placing an order might involve an Order Service, Inventory Service, and Payment Service.

A distributed transaction ensures that all these separate operations either succeed together or fail together, maintaining data consistency across your system.

Beyond Two-Phase Commit

Traditional database transactions often use a Two-Phase Commit (2PC) protocol to ensure atomicity. However, 2PC isn't ideal for microservices because:

  • It creates tight coupling between services.
  • It can lead to long-held locks, impacting availability.
  • It's complex to implement and manage across different technologies.

We need a more flexible approach for distributed systems.

Introducing the Saga Pattern

The Saga pattern is a way to manage distributed transactions. Instead of a single atomic transaction, a saga is a sequence of local transactions, each updating its own service's database.

  • Each local transaction publishes an event upon completion.
  • These events trigger the next step in the saga.
  • If a step fails, compensating transactions are used to undo previous successful steps.

The goal is eventual consistency.

Two Saga Flavors

There are two main ways to implement a Saga:

  • Orchestration: A central "Saga Orchestrator" service manages and directs the workflow, telling each participant what to do next.
  • Choreography: Each service produces and listens to events, deciding its own next action without a central coordinator.

For this lesson, we'll focus on the Orchestration approach, which often pairs well with message brokers like RabbitMQ.

The Brain of the Saga

The Saga Orchestrator is a dedicated service responsible for:

  • Receiving the initial command (e.g., "Create Order").
  • Sending commands to saga participants (microservices).
  • Listening for events from participants.
  • Maintaining the saga's state.
  • Deciding the next step or initiating compensating transactions if a step fails.

RabbitMQ is perfect for the orchestrator to send commands and receive events.

Participants & Local Transactions

A Saga Participant is a microservice involved in the distributed transaction. When it receives a command from the orchestrator, it:

  1. Performs its own local ACID transaction.
  2. Updates its database.
  3. Publishes an event (e.g., "OrderCreatedEvent", "StockReservedEvent") indicating success or failure.

These events are crucial for the orchestrator to continue the saga.

Undo Actions: Compensation

What happens if a step in the saga fails? This is where compensating transactions come in. They are operations designed to reverse the effects of previously completed local transactions.

For example, if a "Process Payment" step fails, a compensating transaction for "Reserve Stock" might be to release the reserved items back into inventory.

This ensures the system returns to a consistent state, even if not fully rolled back.

Orchestrator Kicks Off

Let's imagine an order creation saga. The orchestrator receives a request and sends a command to the first participant (e.g., "Order Service"). Here's a simplified Java example:

public class OrderSagaOrchestrator {
  public void startOrderCreationSaga(String orderId, String userId, double amount) {
    System.out.println("Orchestrator: Starting saga for Order " + orderId);
    // Simulate sending a message to Order Service
    String command = "CreateOrderCommand { orderId: " + orderId + ", userId: " + userId + ", amount: " + amount + " }";
    System.out.println("Orchestrator: Sending command to Order Service: " + command);
    // In a real app, this would be a RabbitMQ message send
  }

  public static void main(String[] args) {
    OrderSagaOrchestrator orchestrator = new OrderSagaOrchestrator();
    orchestrator.startOrderCreationSaga("ORD-001", "user123", 99.99);
  }
}

Participant Responds

Now, let's look at the "Order Service" (a participant) receiving the command. It processes the order locally and then publishes an event.

public class OrderServiceParticipant {
  public void handleCreateOrderCommand(String commandMessage) {
    System.out.println("OrderService: Received command: " + commandMessage);
    // Simulate local transaction (e.g., save order to DB)
    String orderId = "ORD-001"; // Extract from commandMessage in real app
    System.out.println("OrderService: Successfully created local order " + orderId);

    // Simulate publishing an event back to the orchestrator
    String event = "OrderCreatedEvent { orderId: " + orderId + ", status: 'PENDING_PAYMENT' }";
    System.out.println("OrderService: Publishing event: " + event);
    // In a real app, this would be a RabbitMQ message publish
  }

  public static void main(String[] args) {
    OrderServiceParticipant participant = new OrderServiceParticipant();
    participant.handleCreateOrderCommand("CreateOrderCommand { orderId: ORD-001, userId: user123, amount: 99.99 }");
  }
}

Orchestrator Continues Flow

The orchestrator listens for events like OrderCreatedEvent. Upon receiving it, it updates the saga's state and sends the next command, perhaps to an "Inventory Service" to reserve stock.

public class OrderSagaOrchestratorContinued {
  public void handleOrderCreatedEvent(String eventMessage) {
    System.out.println("Orchestrator: Received event: " + eventMessage);
    String orderId = "ORD-001"; // Extract from eventMessage
    // Update saga state (e.g., mark order as 'OrderCreated')

    // Decide next step: send command to Inventory Service
    String command = "ReserveStockCommand { orderId: " + orderId + ", productId: 'PROD-A', quantity: 2 }";
    System.out.println("Orchestrator: Sending command to Inventory Service: " + command);
  }

  public static void main(String[] args) {
    OrderSagaOrchestratorContinued orchestrator = new OrderSagaOrchestratorContinued();
    orchestrator.handleOrderCreatedEvent("OrderCreatedEvent { orderId: ORD-001, status: 'PENDING_PAYMENT' }");
  }
}

Saga Essentials Check

Which of the following are key components or characteristics of the Saga Orchestration pattern?

Saga for Reliability

The Saga pattern is a powerful way to manage complex, long-running distributed transactions in microservice architectures.

  • It enables eventual consistency without tight coupling.
  • It uses local transactions and compensating transactions for resilience.
  • RabbitMQ provides the perfect backbone for the orchestrator and participants to communicate reliably through commands and events.

While adding complexity, Sagas are essential for building robust distributed systems.

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

บทเรียน “รูปแบบ Saga ด้วย RabbitMQ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “รูปแบบ Saga ด้วย RabbitMQ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส RabbitMQ Messaging & Async Systems ให้อัปเกรดเป็น CoddyKit PRO คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “รูปแบบ Saga ด้วย RabbitMQ”

ใช้งานรูปแบบ Saga เพื่อจัดการธุรกรรมแบบกระจายที่ทำงานเป็นเวลานานโดยใช้ RabbitMQ ควบคุมลำดับงานที่ซับซ้อนข้ามไมโครเซอร์วิสหลายตัวได้อย่างน่าเชื่อถือ คุณปฏิบัติ RabbitMQ Messaging & Async Systems ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน RabbitMQ Messaging & Async Systems หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน RabbitMQ Messaging & Async Systems บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “รูปแบบ Saga ด้วย RabbitMQ” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน RabbitMQ Messaging & Async Systems นี้ได้ไหม

ได้ บทเรียน RabbitMQ Messaging & Async Systems ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. ความเป็นไอดีมโพเทนต์ในการประมวลผลข้อความ
  2. รูปแบบ Saga ด้วย RabbitMQ
  3. การแยกความรับผิดชอบคำสั่งและการสอบถาม (CQRS)
  4. รูปแบบ Outbox สำหรับการเผยแพร่ที่เชื่อถือได้
← กลับไปที่ RabbitMQ Messaging & Async Systems