Temporal 拥有免费持久工作流引擎,永不丢失你的状态

发布: (2026年3月30日 GMT+8 02:20)
4 分钟阅读
原文: Dev.to

Source: Dev.to

(未提供需要翻译的正文内容。)

Introduction

当你的支付处理在交易中途崩溃时会怎样?
使用普通代码——数据丢失。
使用 Temporal——它会在恰好中断的地方恢复。Temporal 默认使你的工作流具备持久性、可靠性和可恢复性。

核心优势

  • Durable execution – 工作流在崩溃、重启和部署后仍能继续运行。
  • Automatic retries – 可为每个活动配置重试策略。
  • Long‑running workflows – 可运行数天、数周或数月。
  • Timers – 在不占用资源的情况下休眠数小时/天。
  • Versioning – 更新工作流代码而不影响正在运行的实例。
  • Visibility – Web UI 显示所有工作流状态。
  • TypeScript SDK – 完全类型化,提供出色的开发者体验。
  • Self‑hosted – 支持 Docker Compose 或 Kubernetes。

入门

运行 Temporal 服务器

docker compose up -d

创建项目

npx @temporalio/create@latest my-app
cd my-app
npm run start

工作流示例 (workflows.ts)

import { proxyActivities, sleep } from '@temporalio/workflow';
import type * as activities from './activities';

const { sendEmail, chargePayment, provisionAccount } = proxyActivities({
  startToCloseTimeout: '30 seconds',
  retry: { maximumAttempts: 3 }
});

export async function onboardUser(email: string, plan: string): Promise {
  // Step 1: Send welcome email
  await sendEmail(email, 'Welcome!');

  // Step 2: Charge payment
  const paymentId = await chargePayment(email, plan);

  // Step 3: Provision account
  await provisionAccount(email, plan);

  // Step 4: Wait 3 days, then send tips
  await sleep('3 days'); // Durable! Survives server restarts.
  await sendEmail(email, 'Here are some tips...');

  // Step 5: Wait 7 days, check engagement
  await sleep('7 days');
  await sendEmail(email, "How's it going?");
}

如果服务器在 第 2 步 之后崩溃,Temporal 将在 第 3 步 继续执行——而不是从头开始。

活动 (activities.ts)

export async function sendEmail(to: string, subject: string): Promise {
  await resend.emails.send({ to, subject, from: 'app@company.com' });
}

export async function chargePayment(email: string, plan: string): Promise {
  const session = await stripe.checkout.sessions.create({
    customer_email: email,
    line_items: [{ price: plans[plan], quantity: 1 }]
  });
  return session.id;
}

export async function provisionAccount(email: string, plan: string): Promise {
  await db.accounts.create({ data: { email, plan, status: 'active' } });
}

启动工作流 (client.ts)

import { Client } from '@temporalio/client';

const client = new Client();

const handle = await client.workflow.start('onboardUser', {
  taskQueue: 'main',
  workflowId: `onboard-${userId}`,
  args: ['user@example.com', 'pro']
});

// Check status
const result = await handle.result();

典型使用场景

  • Payment processing – 收费、履行、退款,保证完成。
  • User onboarding – 多天序列,状态永不丢失。
  • Data pipelines – ETL 作业,可从失败点恢复。
  • Order fulfillment – 支付 → 库存 → 发货 → 通知。
  • Subscription management – 计费周期、升级、取消。

功能比较

功能TemporalBullMQInngestTrigger.dev
持久执行✅ Core feature
长时间运行天/个月小时有限小时
工作流状态自动手动自动手动
版本管理内置
可视化界面完整Bull Board仪表盘仪表盘
自托管✅ (Redis)
复杂度中等

结论

Temporal 是理想的工作流解决方案,适用于 must 完成的任务——支付处理、订单履行、数据管道等。当崩溃或重启可能导致状态丢失时,Temporal 能保证持久性和可靠性,为任何应用提供企业级弹性。

0 浏览
Back to Blog

相关文章

阅读更多 »

为什么学习 Node.js?

为什么要学习 Node.js?如果你正踏入开发世界或想要提升为程序员,学习 Node.js 可以成为最具战略性的决定之一……