编排式 Saga 详解
了解编舞式方法:各服务通过事件直接通信,无需中央协调器。
编排式 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 节课。
本课时的部分内容尚未翻译,以英文显示。
Choreography Saga Intro
Welcome! In this lesson, we'll explore the Choreography Saga pattern. It's a way to manage complex business transactions that span multiple services in a decentralized way.
Unlike an orchestra with a conductor, choreography is like a dance where each dancer knows their part and reacts to others' movements.
Decentralized Event Flow
In a choreography saga, there's no central coordinator service. Instead, each service involved in the transaction publishes events and listens for events from other services.
- Services react to events.
- They perform their part of the transaction.
- They publish new events to trigger the next step.
Order Processing Example
Let's use a common example: processing a customer order. This involves multiple steps across different services:
- Order Service: Creates the order.
- Payment Service: Handles payment.
- Inventory Service: Updates stock.
How do these services coordinate without a central brain?
Step 1: Order Created Event
When a customer places an order, the Order Service starts the saga. It saves the order and then publishes an OrderCreatedEvent.
This event signals to other services that a new order is ready for processing.
public class OrderService {
public static void processNewOrder(String orderId) {
System.out.println("Order Service: Received new order " + orderId);
System.out.println("Order Service: Saving order " + orderId + " to database...");
// Imagine database interaction here
System.out.println("Order Service: Order " + orderId + " saved.");
System.out.println("Order Service: Publishing 'OrderCreatedEvent' for " + orderId);
}
public static void main(String[] args) {
processNewOrder("ORD789"); // Simulate a new order coming in
}
}Step 2: Payment Service Reacts
The Payment Service is subscribed to OrderCreatedEvents. When it receives one, it processes the payment for that order.
After processing, it publishes either a PaymentProcessedEvent or a PaymentFailedEvent.
public class PaymentService {
public static void handleOrderCreated(String orderId) {
System.out.println("Payment Service: Received 'OrderCreatedEvent' for order " + orderId);
System.out.println("Payment Service: Processing payment for " + orderId + "...");
// Simulate payment gateway interaction
boolean paymentSuccess = true; // For this example, assume success
if (paymentSuccess) {
System.out.println("Payment Service: Payment successful for " + orderId + ".");
System.out.println("Payment Service: Publishing 'PaymentProcessedEvent' for " + orderId);
} else {
System.out.println("Payment Service: Payment failed for " + orderId + ".");
System.out.println("Payment Service: Publishing 'PaymentFailedEvent' for " + orderId);
}
}
public static void main(String[] args) {
handleOrderCreated("ORD789"); // Simulate receiving an event
}
}Step 3: Inventory Service Updates
Next, the Inventory Service listens for PaymentProcessedEvents. Upon receiving one, it reduces the stock for the ordered items.
It then publishes an InventoryUpdatedEvent to indicate its task is complete.
public class InventoryService {
public static void handlePaymentProcessed(String orderId) {
System.out.println("Inventory Service: Received 'PaymentProcessedEvent' for order " + orderId);
System.out.println("Inventory Service: Updating stock for order " + orderId + "...");
// Simulate inventory database update
System.out.println("Inventory Service: Stock updated for order " + orderId + ".");
System.out.println("Inventory Service: Publishing 'InventoryUpdatedEvent' for " + orderId);
}
public static void main(String[] args) {
handlePaymentProcessed("ORD789"); // Simulate receiving an event
}
}The Challenge of Failures
What happens if a step in this flow fails? For example, if the payment fails, we can't update inventory. We also need to undo any previous successful steps.
This is where compensation logic comes in. It's about reversing previously completed actions.
Compensation in Choreography
In a choreography saga, compensation also happens through events. If a service fails, it publishes a compensation event.
Other services listen for these compensation events and perform their own rollback actions.
Compensation Example: Payment Fails
Imagine the Payment Service fails and publishes a PaymentFailedEvent. The Order Service, which started the saga, listens for this event.
Upon receiving it, the Order Service updates the order status to 'Cancelled', effectively rolling back the transaction from its side.
public class OrderService {
public static void handlePaymentFailed(String orderId) {
System.out.println("Order Service: Received 'PaymentFailedEvent' for order " + orderId);
System.out.println("Order Service: Initiating compensation for " + orderId + ".");
// Change order status to 'Cancelled'
System.out.println("Order Service: Updating order " + orderId + " status to 'Cancelled'.");
// Could publish OrderCancelledEvent if other services need to know
}
public static void main(String[] args) {
handlePaymentFailed("ORD789"); // Simulate receiving a compensation event
}
}Pros and Cons of Choreography
Choreography offers benefits but also presents challenges:
- Pros: Highly decoupled services, no central point of failure, simpler to implement for simple flows.
- Cons: Can be harder to monitor the overall transaction flow, complex compensation logic, potential for 'event storms' if not designed carefully.
Choreography Check
Consider a choreography saga where an 'OrderConfirmedEvent' is published. Which statement accurately describes how the next step is initiated?
Recap: Choreography Saga
You've learned about the Choreography Saga pattern:
- It's a decentralized approach for distributed transactions.
- Services communicate by publishing and subscribing to events.
- There's no central coordinator; each service knows its role.
- Compensation for failures is also handled via events, allowing services to roll back their actions.
This pattern promotes loose coupling but requires careful design for monitoring and compensation.
常见问题解答
「编排式 Saga 详解」课时是免费的吗?
是的 — 「编排式 Saga 详解」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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 节。
「编排式 Saga 详解」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Microservices Communication Patterns (Saga, Circuit Breaker) 课中编写并运行代码吗?
能。每节 Microservices Communication Patterns (Saga, Circuit Breaker) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 什么是 Saga 模式
- 编排式 Saga 详解
- 编排式 Saga 详解
- 在编排与协同之间做出选择