使用事件处理补偿
在编舞式 Saga 中发布特定的回滚事件来撤销先前操作,实现补偿步骤。
使用事件处理补偿 是 CoddyKit 上的免费 Microservices Communication Patterns (Saga, Circuit Breaker) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Microservices Communication Patterns (Saga, Circuit Breaker) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Compensation is Crucial
In choreography sagas, services react to events. But what happens when one of those services fails to complete its part of a distributed transaction?
We need a way to undo any actions that were successfully performed by previous services. This is where compensation comes in.
What is Compensation?
Compensation is the process of reversing previously completed operations within a distributed transaction. Think of it as a 'rollback' mechanism tailored for microservices.
It ensures that if any step in a multi-service business process fails, the system can return to a consistent state.
Compensation in Choreography
In a choreography saga, there's no central orchestrator. Services communicate directly via events. So, how do we trigger compensation?
- When a service fails to complete its task, it publishes a specific compensation event.
- Other services that have successfully completed their part listen for these compensation events.
- Upon receiving a compensation event, they execute their own rollback logic.
Designing Compensation Events
Compensation events must contain enough information for services to perform their rollback. Key details often include:
- The original saga ID or transaction ID.
- Details about the original action that needs to be reversed.
- Any data required to perform the reversal (e.g., amount to refund, item to unreserve).
Example: Order Processing Saga
Consider an online order process:
- Order Service: Creates order (publishes
OrderCreated) - Payment Service: Processes payment (publishes
PaymentProcessed) - Inventory Service: Reserves stock (publishes
InventoryReserved)
What if the Inventory Service fails to reserve stock?
Initiating the Rollback
If the Inventory Service fails to reserve stock, it should:
- Not publish
InventoryReserved. - Instead, publish a compensation event, like
InventoryReservationFailed.
This event signals to other services that the saga could not complete successfully and they need to undo their actions.
Payment Service's Compensation
The Payment Service is subscribed to events that indicate failures. When it receives InventoryReservationFailed, it knows it needs to act:
- It will initiate a refund for the payment it previously processed.
- After refunding, it might publish a new event, like
PaymentRefunded, to inform other interested services.
Order Service's Compensation
The Order Service, having created the initial order, also needs to react. It might listen for InventoryReservationFailed or PaymentRefunded.
- Upon receiving such an event, the Order Service updates the order's status to 'Cancelled' or 'Failed'.
- This ensures the user sees an accurate status for their order.
Implementing Compensation Logic
Each service must contain logic to handle both successful forward-progress events and specific compensation events. This often means having separate event handlers for each.
Here's a simplified example of how a Payment Service might listen for a compensation event and trigger a refund:
public class PaymentService {
public static void main(String[] args) {
System.out.println("Payment Service Started.");
// Simulate receiving an event from a message broker
String receivedEvent = "InventoryReservationFailed: Order123";
if (receivedEvent.startsWith("InventoryReservationFailed")) {
String orderId = receivedEvent.split(":")[1];
System.out.println("Received compensation event: " + receivedEvent);
System.out.println("Initiating refund for Order ID: " + orderId + "...");
// In a real system, call a payment gateway API to refund
boolean refundSuccess = processRefund(orderId);
if (refundSuccess) {
System.out.println("Refund processed successfully for " + orderId + ".");
// Publish 'PaymentRefunded' event for other services
System.out.println("Publishing PaymentRefunded event.");
} else {
System.out.println("Refund failed for " + orderId + ".");
// Handle refund failure (e.g., alert, manual intervention)
}
} else {
System.out.println("No compensation event received yet.");
}
System.out.println("Payment Service Shutting Down.");
}
private static boolean processRefund(String orderId) {
// Simulate external refund API call
return true; // Assume success for this example
}
}Quick Check: Compensation Purpose
In a choreography saga, if the 'Inventory Service' fails to reserve items after 'Payment Service' has processed a payment, what is the primary purpose of the 'Inventory Service' publishing an InventoryReservationFailed event?
Recap: Handling Compensation
You've learned how critical compensation is in choreography sagas to maintain data consistency in distributed systems. Key takeaways:
- Compensation reverses successful actions when a saga step fails.
- In choreography, services publish specific compensation events to initiate rollbacks.
- Each service must implement logic to listen for and react to these events, performing its own undo operations.
- Clear event design and robust handling are essential for resilient sagas.
常见问题解答
「使用事件处理补偿」课时是免费的吗?
是的 — 「使用事件处理补偿」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用事件处理补偿」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Microservices Communication Patterns (Saga, Circuit Breaker) 课中编写并运行代码吗?
能。每节 Microservices Communication Patterns (Saga, Circuit Breaker) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 设计事件驱动的 Saga
- 事件总线与消息代理
- 使用事件处理补偿
- 构建幂等事件消费者