Class Saga<T>
java.lang.Object
cloud.opencode.base.event.saga.Saga<T>
- Type Parameters:
T- the saga context type - saga 上下文类型Security | 安全性:
- Thread-safe: No - 线程安全: 否
Saga - Distributed Transaction Orchestration Pattern
Saga - 分布式事务编排模式
Implements the Saga pattern for managing distributed transactions through a sequence of local transactions with compensating actions for rollback.
实现 Saga 模式,通过一系列本地事务和补偿操作来管理分布式事务。
Features | 主要功能:
- Step-based transaction orchestration - 基于步骤的事务编排
- Automatic compensation on failure - 失败时自动补偿
- Async execution support - 异步执行支持
- Timeout handling - 超时处理
- Retry policies - 重试策略
- State persistence - 状态持久化
Usage Examples | 使用示例:
// Define a saga for order processing
Saga<OrderContext> orderSaga = Saga.<OrderContext>builder()
.name("order-processing")
.step("reserve-inventory")
.action(ctx -> inventoryService.reserve(ctx.getOrderId(), ctx.getItems()))
.compensation(ctx -> inventoryService.release(ctx.getOrderId()))
.timeout(Duration.ofSeconds(30))
.retries(3)
.build()
.step("process-payment")
.action(ctx -> paymentService.charge(ctx.getOrderId(), ctx.getAmount()))
.compensation(ctx -> paymentService.refund(ctx.getOrderId()))
.timeout(Duration.ofSeconds(60))
.build()
.step("ship-order")
.action(ctx -> shippingService.ship(ctx.getOrderId()))
.compensation(ctx -> shippingService.cancel(ctx.getOrderId()))
.build()
.onSuccess(ctx -> notificationService.notifyOrderComplete(ctx))
.onFailure((ctx, error) -> notificationService.notifyOrderFailed(ctx, error))
.build();
// Execute the saga
SagaResult<OrderContext> result = orderSaga.execute(new OrderContext(orderId, items, amount));
// Or execute async
CompletableFuture<SagaResult<OrderContext>> future = orderSaga.executeAsync(context);
- Since:
- JDK 25, opencode-base-event V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classBuilder for Saga.static classException thrown when a saga step times out. saga 步骤超时时抛出的异常。static final classBuilder for SagaStep. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Saga.Builder<T> builder()Creates a new builder.Executes the saga synchronously.executeAsync(T context) Executes the saga asynchronously.getName()Gets the saga name.intGets the number of steps.Gets the step names.
-
Method Details
-
execute
Executes the saga synchronously. 同步执行 saga。- Parameters:
context- the saga context - saga 上下文- Returns:
- the saga result - saga 结果
-
executeAsync
Executes the saga asynchronously. 异步执行 saga。- Parameters:
context- the saga context - saga 上下文- Returns:
- CompletableFuture with saga result - 包含 saga 结果的 CompletableFuture
-
getName
Gets the saga name. 获取 saga 名称。 -
getStepCount
public int getStepCount()Gets the number of steps. 获取步骤数量。 -
getStepNames
-
builder
Creates a new builder. 创建新的构建器。- Type Parameters:
T- the context type - 上下文类型- Returns:
- the builder - 构建器
-