---
title: "微服务编排"
description: "一个 Flow 最多调用四个 API。API 2 和 API 3 并行运行。API 3 的分支先等待回调或 24 小时超时，再发出调用。"
canonical_url: "https://docs.superdurable.io/zh-Hans/examples/microservice-orchestration/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/use-cases/microservice-orchestration.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 微服务编排

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/examples/microservice-orchestration.go.md) · [Java](https://docs.superdurable.io/zh-Hans/examples/microservice-orchestration.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/examples/microservice-orchestration.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/examples/microservice-orchestration.rust.md)

一个 Flow 最多调用四个 API。API 2 和 API 3 并行运行。API 3 的分支先等待回调或 24 小时超时，再发出调用。

**SDK：** Python · Go · TypeScript · Java · Rust

**展示：**[静态并行 Step](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/static-parallel-steps.md) 和[带截止时间的决定](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/decision-with-deadline.md)。

**Flow 图：OrchestrationFlow**

**Step 列表**

1. `CallAPI1`（起始 Step）：Call API 1, store its data, and call APIs 2 and 3 in parallel. 下一步：`CallAPI2`，或 `CallAPI3`。 写入 `data`。
2. `CallAPI2`：Call API 2 with the stored data. 下一步：这个分支结束。 读取 `data`。
3. `CallAPI3`：Wait for the ready signal or 24 hours, then call API 3. 下一步：`CallAPI4`，或 Flow 完成。 读取 `data`。
4. `CallAPI4`：Call API 4 when the ready signal did not arrive in time. 下一步：Flow 完成。 读取 `data`。

**RPC 列表**

- `get_data`：读取 `data`。
- `signal_ready`：发布到 `Ready`。
- `swap`：读取 `data`；锁定 `data`；写入 `data`。

例子: [examples/python/dex_examples/products/microservices/orchestration_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/microservices/orchestration_flow.py)

上图和下面说明中的名称来自 Python 示例。Rust 示例使用另一套名称，见 [Rust 示例](https://docs.superdurable.io/zh-Hans/examples/microservice-orchestration.md#rust-example)。

<a id="product-requirements"></a>

## 产品需求

<a id="产品需求"></a>

流程以一个数据值启动。它必须：

1. 调用 API 1，并保存这个值。
2. 然后并行调用 API 2 和 API 3。
3. 调用 API 3 之前，等另一个服务报告就绪，最多等 24 小时。
4. 如果先过了 24 小时，在 API 3 之后再调用 API 4。
5. 流程运行期间，允许调用方交换这个值：在一次操作中存入新值并取回旧值。

API 2、API 3 和 API 4 使用各自运行时的当前值。

<a id="flow-design"></a>

## Flow 设计

<a id="flow-设计"></a>

`CallAPI1` 把值存入 `data` Attribute，并把 `CallAPI2` 和 `CallAPI3` 作为并行 Step 启动。每个 API 调用都是一个独立的 Step。所以重试 API 3 不会重复 API 1 或 API 2。

`CallAPI2` 返回 `DeadEnd`，结束自己的分支。另一个分支完成 Flow。

`CallAPI3` 用 `AnyOf` 等待一条 `Ready` Channel 消息或一个 24 小时的 Timer。它的 Execute 调用 API 3，然后检查 Timer 是否触发。如果触发了，Flow 继续到 `CallAPI4`。

**Swap** RPC 锁住 `data`，写入新值并返回旧值。每个分支在运行时读取 `data`。所以如果交换发生在两次读取之间，`CallAPI2` 和 `CallAPI3` 会拿到不同的值。

真实的 API 调用需要[幂等键](https://docs.superdurable.io/zh-Hans/concepts/step.md#idempotency-keys)，因为被中断的 Step 可能再次运行。示例没有传：它调用的是本地 stub。

<a id="core-implementation"></a>

## 核心实现

<a id="核心实现"></a>

每个标签页先展示带 **Swap** RPC 的 Flow，再展示 `CallAPI1` 和 `CallAPI3`。

**Python**

```python
class OrchestrationFlow(Flow[str]):
    data = Attribute("data", str)
    ready = Channel[None]("Ready", type(None))

    def __init__(self, service: MyDependencyService) -> None:
        self.service = service
        self.call_api4 = CallAPI4(service, self.data)
        self.call_api3 = CallAPI3(service, self.data, self.ready, self.call_api4)
        self.call_api2 = CallAPI2(service, self.data)
        self.call_api1 = CallAPI1(service, self.data, self.call_api2, self.call_api3)

    def get_steps(self) -> StepList[str]:
        return StepList.start_step(self.call_api1).other_steps(
            self.call_api2,
            self.call_api3,
            self.call_api4,
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(self.data, self.ready)

    @rpc(lock_attributes=(data.lock(),))
    def swap(self, context: Context, new_data: str) -> RPCResult[str]:
        old_data = self.data.get(context)
        # CallAPI1 would overwrite a value written before it stores data.
        if old_data is None:
            raise RuntimeError("data is not ready yet")
        self.data.set(context, new_data)
        return RPCResult(old_data)
```

```python
class CallAPI1(Step[str]):
    def __init__(
        self,
        service: MyDependencyService,
        data: Attribute[str],
        call_api2: CallAPI2,
        call_api3: CallAPI3,
    ) -> None:
        self.service = service
        self.data = data
        self.call_api2 = call_api2
        self.call_api3 = call_api3

    def execute(self, context: Context, input: str) -> StepDecision:
        self.service.call_api1(input)
        self.data.set(context, input)
        return go_to_many(
            StepMovement.of(CallAPI2, None),
            StepMovement.of(CallAPI3, None),
        )
```

```python
class CallAPI3(Step[None]):
    def __init__(
        self,
        service: MyDependencyService,
        data: Attribute[str],
        ready: Channel[None],
        call_api4: CallAPI4,
    ) -> None:
        self.service = service
        self.data = data
        self.ready = ready
        self.call_api4 = call_api4

    def wait_for(self, context: Context, input: None) -> Wait:
        return Wait.any_of(
            Timer.by_duration(timedelta(hours=24)),
            self.ready.for_one(),
        )

    def execute(self, context: Context, input: None) -> StepDecision:
        value = self.data.get(context)
        self.service.call_api3(value)
        if context.has_timer_fired():
            return go_to(CallAPI4, None)
        return graceful_complete(value)
```

例子: [examples/python/dex_examples/products/microservices/orchestration_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/microservices/orchestration_flow.py)

<a id="rust-example"></a>

## Rust 示例

Rust 示例用另一套名称运行同一个 Flow。它的 Attribute 是 `orchestration-data`，Channel 是 `orchestration-ready`，Step 是 `CallApiOne` 到 `CallApiFour`。每个 Step 记录一个事件，代替 API 调用。[运行](https://docs.superdurable.io/zh-Hans/examples/microservice-orchestration.md#run-it)中的调用对它同样适用。

<a id="run-it"></a>

## 运行

<a id="demo"></a>

<a id="演示"></a>

按[在 playground 里运行一个示例](https://docs.superdurable.io/zh-Hans/install.md#run-an-example-from-the-playground)启动一种语言的示例。在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 中选择 **Microservices**，用同一个 Flow ID 依次调用 **Start**、**Swap data (RPC)** 和 **Signal ready**。`CallAPI1` 保存值之前，**Swap** 会失败；这时再调用一次即可。

下面的截图来自一次使用自选值的运行。它以 `initial-data` 启动，**Swap** 把它替换为 `updated-data`。playground 以 `test initial data` 启动，并换入 **data** 字段的值。**Ready** 在 Timer 触发前到达，所以 `CallAPI4` 没有运行。

在 Dex Web 中打开 **Events**。**Timeline** 显示 **Swap** RPC 和 **Ready** 消息，**Graph** 显示哪些 Step 运行了。

[![Dex Web Timeline 展示编排运行中的 Swap 和 Signal Ready 调用](https://docs.superdurable.io/img/use-cases/microservice-orchestration-timeline.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/microservice-orchestration-timeline.png)

[![Dex Web Graph 展示编排运行中的 Swap 和 Signal Ready 调用](https://docs.superdurable.io/img/use-cases/microservice-orchestration-graph.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/microservice-orchestration-graph.png)

<a id="next"></a>

## 下一步

<a id="下一步"></a>

- [职位发布](https://docs.superdurable.io/zh-Hans/examples/job-posting.md)
- [静态并行 Step](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/static-parallel-steps.md)
- [带截止时间的决定](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/decision-with-deadline.md)
- [Channel](https://docs.superdurable.io/zh-Hans/concepts/primitives/channel.md)
- [Timer](https://docs.superdurable.io/zh-Hans/concepts/primitives/timer.md)
- [RPC](https://docs.superdurable.io/zh-Hans/concepts/primitives/rpc.md)
- [Attribute](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md)
