提交工单

香港服务器部署Temporal工作流引擎:可靠分布式任务编排完整实战

Celery 任务失败了,你需要手动重试;长时间运行的流程中途崩溃,从头开始重新跑。Temporal 从根本上解决这个问题:工作流的每一步状态都持久化到数据库,即使服务器崩溃重启,工作流从中断处自动恢复,对应用层完全透明。


一、Temporal vs 传统任务队列

维度TemporalCelery/RQAirflow
故障自动恢复✅ 从中断处继续❌ 需要手动处理△ 任务级别重试
长时间运行任务✅(天/月级别)有超时限制✅
状态持久化✅ 自动❌✅
复杂工作流✅ 代码即工作流有限✅ DAG
适合场景业务流程、长任务简单异步任务数据管道

二、Docker 部署

<code"># /opt/temporal/docker-compose.yml
version: '3.8'
services:
  temporal:
    image: temporalio/auto-setup:latest
    container_name: temporal
    restart: unless-stopped
    ports:
      - "127.0.0.1:7233:7233"
    environment:
      DB: postgresql
      DB_PORT: 5432
      POSTGRES_USER: temporal
      POSTGRES_PWD: temporal_pass
      POSTGRES_SEEDS: postgres
    depends_on:
      - postgres

  temporal-ui:
    image: temporalio/ui:latest
    container_name: temporal-ui
    ports:
      - "127.0.0.1:8233:8080"
    environment:
      TEMPORAL_ADDRESS: temporal:7233

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: temporal
      POSTGRES_USER: temporal
      POSTGRES_PASSWORD: temporal_pass
    volumes:
      - /opt/temporal/postgres:/var/lib/postgresql/data

cd /opt/temporal && docker compose up -d

三、Python Worker 实现订单处理工作流

<code">from temporalio import activity, workflow
from temporalio.client import Client
from temporalio.worker import Worker
from datetime import timedelta
import asyncio

# ── 定义 Activities(实际执行的业务逻辑)──
@activity.defn
async def validate_payment(order_id: str) -> bool:
    """验证支付是否到账"""
    # 调用支付 API 检查
    result = await payment_service.check(order_id)
    return result.is_paid

@activity.defn
async def allocate_inventory(order_id: str) -> dict:
    """扣减库存"""
    return await inventory_service.allocate(order_id)

@activity.defn
async def trigger_shipping(order_id: str, inventory: dict):
    """触发发货"""
    await logistics_service.create_shipment(order_id, inventory)

@activity.defn
async def send_confirmation_email(order_id: str):
    """发送确认邮件"""
    await email_service.send_order_confirmation(order_id)

# ── 定义 Workflow(编排 Activities)──
@workflow.defn
class OrderFulfillmentWorkflow:
    @workflow.run
    async def run(self, order_id: str) -> str:
        """
        订单履约工作流:
        即使任意步骤失败,Temporal 自动重试;
        即使服务器崩溃,重启后从中断处继续
        """
        # Step 1: 等待支付确认(最长等待1天)
        is_paid = await workflow.execute_activity(
            validate_payment,
            order_id,
            schedule_to_close_timeout=timedelta(days=1),  # 1天超时
            retry_policy=RetryPolicy(maximum_attempts=10)
        )

        if not is_paid:
            return f"Order {order_id}: payment not received, cancelled"

        # Step 2: 扣减库存(最长等待1分钟,失败重试5次)
        inventory = await workflow.execute_activity(
            allocate_inventory,
            order_id,
            schedule_to_close_timeout=timedelta(minutes=1),
            retry_policy=RetryPolicy(maximum_attempts=5)
        )

        # Step 3: 触发发货
        await workflow.execute_activity(
            trigger_shipping,
            order_id,
            inventory,
            schedule_to_close_timeout=timedelta(minutes=5)
        )

        # Step 4: 发送确认邮件(失败不影响主流程)
        await workflow.execute_activity(
            send_confirmation_email,
            order_id,
            schedule_to_close_timeout=timedelta(minutes=1),
            retry_policy=RetryPolicy(maximum_attempts=3)
        )

        return f"Order {order_id}: fulfilled successfully"

# ── 启动 Worker ──
async def main():
    client = await Client.connect("localhost:7233")
    worker = Worker(
        client,
        task_queue="order-fulfillment",
        workflows=[OrderFulfillmentWorkflow],
        activities=[validate_payment, allocate_inventory,
                    trigger_shipping, send_confirmation_email]
    )
    await worker.run()

asyncio.run(main())

四、触发工作流

<code">from temporalio.client import Client

async def process_order(order_id: str):
    client = await Client.connect("localhost:7233")

    # 启动工作流(幂等:同一 workflow_id 不会重复创建)
    handle = await client.start_workflow(
        OrderFulfillmentWorkflow.run,
        order_id,
        id=f"order-fulfillment-{order_id}",  # 唯一 ID
        task_queue="order-fulfillment",
    )

    print(f"工作流已启动: {handle.id}")

    # 可以等待结果,也可以异步处理
    result = await handle.result()
    print(f"工作流完成: {result}")

五、总结

Temporal 将「可靠性」从应用层的关注点变成了基础设施能力——开发者专注于业务逻辑,不需要自己实现重试、状态管理和故障恢复。香港服务器上运行 Temporal,特别适合跨境电商的订单处理(支付确认→库存→发货→通知)、数据同步任务、定期报表生成等长时间运行且对可靠性要求高的业务场景。

Telegram
Telegram服务器销售@IDCSELL
Telegram技术支持@IDCService