0Pricing
Microservices Communication Patterns (Saga, Circuit Breaker) · 课时

用于编排的状态机

应用状态机概念,构建能够跟踪事务进度的健壮且可预测的 Saga 编排器。

用于编排的状态机 是 CoddyKit 上的免费 Microservices Communication Patterns (Saga, Circuit Breaker) 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Microservices Communication Patterns (Saga, Circuit Breaker) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

State Machines for Sagas

Welcome to this lesson on using state machines to build robust saga orchestrators!

Orchestration sagas manage complex distributed transactions by keeping track of the overall process. State machines are a powerful tool for this.

Why State Machines?

A saga orchestrator needs to know the exact status of a business process at any given moment. This allows it to:

  • Decide the next action to take.
  • Handle failures and trigger compensation.
  • Ensure consistency across multiple services.

State machines provide a clear, structured way to model this complex logic.

State Machine Basics

At its core, a state machine consists of three main concepts:

  • States: Represent different phases or conditions of the saga (e.g., OrderCreated, PaymentPending).
  • Events: Occurrences that trigger changes in the saga (e.g., PaymentSuccessful, ShipmentFailed).
  • Transitions: Rules that define how an event causes the saga to move from one state to another.

Example: Order Processing Saga

Let's consider a common scenario: an online order processing saga.

This saga might involve several services:

  • Order Service
  • Payment Service
  • Shipping Service

The orchestrator needs to coordinate these steps.

Defining Saga States

For our order processing saga, we can define states like:

  • ORDER_CREATED: Initial state.
  • PAYMENT_PENDING: Waiting for payment confirmation.
  • PAID: Payment successful.
  • SHIPPING_PENDING: Waiting for shipment to be initiated.
  • SHIPPED: Item has been shipped.
  • CANCELLED: Order cancelled (due to failure or user action).

Defining Saga Events

And the events that can occur:

  • ORDER_PLACED: Customer places an order.
  • PAYMENT_SUCCESS: Payment service confirms payment.
  • PAYMENT_FAILED: Payment service reports failure.
  • SHIPMENT_SUCCESS: Shipping service confirms shipment.
  • SHIPMENT_FAILED: Shipping service reports an issue.
  • ORDER_CANCELLED_REQUEST: User requests cancellation.

State Transition Logic

The core of a state machine is its transition logic: Current State + Event = New State (and possibly an action).

For example:

  • If in ORDER_CREATED state and ORDER_PLACED event occurs, transition to PAYMENT_PENDING.
  • If in PAYMENT_PENDING state and PAYMENT_SUCCESS event occurs, transition to PAID.

This defines the predictable flow of your saga.

Code: Simple State Transition

Here's a simplified Java example demonstrating how states and events can drive transitions in an orchestrator.

Try running it to see the state changes!

public class SimpleSagaState {

    public enum SagaStepState {
        STARTED,
        PROCESSING_PAYMENT,
        PAYMENT_COMPLETE,
        FAILED
    }

    private SagaStepState currentState;

    public SimpleSagaState() {
        this.currentState = SagaStepState.STARTED;
    }

    public SagaStepState getCurrentState() {
        return currentState;
    }

    public void processEvent(String event) {
        System.out.println("Event: " + event);
        switch (currentState) {
            case STARTED:
                if ("OrderCreated".equals(event)) {
                    currentState = SagaStepState.PROCESSING_PAYMENT;
                }
                break;
            case PROCESSING_PAYMENT:
                if ("PaymentSuccess".equals(event)) {
                    currentState = SagaStepState.PAYMENT_COMPLETE;
                } else if ("PaymentFailed".equals(event)) {
                    currentState = SagaStepState.FAILED;
                }
                break;
            case PAYMENT_COMPLETE:
                // After payment, might go to shipping, etc.
                break;
            case FAILED:
                System.out.println("Saga already failed.");
                break;
        }
        System.out.println("New State: " + currentState);
    }

    public static void main(String[] args) {
        SimpleSagaState saga = new SimpleSagaState();
        System.out.println("Initial State: " + saga.getCurrentState());

        saga.processEvent("OrderCreated");
        saga.processEvent("PaymentSuccess");
        saga.processEvent("ShipmentInitiated"); // This event won't change state in this simplified example

        System.out.println("Final State: " + saga.getCurrentState());
    }
}

Compensation with States

One of the biggest advantages of using state machines for sagas is how they simplify compensation logic.

If a service fails, the orchestrator receives a 'failed' event. Based on the current state, the state machine can determine which compensation actions need to be triggered to reverse previous successful steps.

For example, if in PAID state and SHIPMENT_FAILED occurs, the state machine can transition to CANCELLED and trigger a refund.

State Transition Question

Consider an order saga using a state machine. The order is currently in the PAYMENT_PENDING state.

If the orchestrator receives a PAYMENT_FAILED event, what is the most appropriate next state for the saga, typically indicating compensation?

Recap: States for Orchestration

In this lesson, we explored how state machines are crucial for building robust saga orchestrators.

  • They provide a clear model for tracking saga progress.
  • States, Events, and Transitions define the saga's flow.
  • They simplify handling complex logic, especially for compensation.

By explicitly defining states and transitions, you create predictable and resilient distributed transactions.

常见问题解答

「用于编排的状态机」课时是免费的吗?

是的 — 「用于编排的状态机」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Microservices Communication Patterns (Saga, Circuit Breaker) 课程的其余内容,请升级到 CoddyKit PRO。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。

「用于编排的状态机」这节课中我会学到什么?

应用状态机概念,构建能够跟踪事务进度的健壮且可预测的 Saga 编排器。 你通过在浏览器中直接运行的动手代码来练习 Microservices Communication Patterns (Saga, Circuit Breaker),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Microservices Communication Patterns (Saga, Circuit Breaker) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Microservices Communication Patterns (Saga, Circuit Breaker) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「用于编排的状态机」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Microservices Communication Patterns (Saga, Circuit Breaker) 课中编写并运行代码吗?

能。每节 Microservices Communication Patterns (Saga, Circuit Breaker) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设计 Saga 编排器
  2. 用于编排的状态机
  3. 使用工作流引擎实现
  4. 测试编排式 Saga
← 返回 Microservices Communication Patterns (Saga, Circuit Breaker)