运维部署
需要编写生产级 Apache Airflow DAG…
在创建、测试或调试 Airflow 数据管道与批处理调度 DAG 时,按生产级 DAG、operator、sensor 和测试模式落地。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 60/100 ×0.15
适用场景
需要编写生产级 Apache Airfl特定
解决思路
- 设计 DAG 时遵循四项原则:任务幂等(重复运行得到相同结果)、原子性(任务要么完全成功要么完全失败)、增量处理(只处理新增或变更数据)、可观测(每一步都有日志、指标和告警)。
- 用依赖性语法表达任务关系:线性用 `task1 >> task2 >> task3`;扇出用 `task1 >> [task2, task3, task4]`;扇入用 `[task1, task2, task3] >> task4`;复杂依赖拆成多条链,如 `task1 >> task2 >> task4` 和 `task1 >> task3 >> task4`。
- 按 Quick Start 在 `dags/example_dag.py` 中创建 DAG:导入 `datetime`、`timedelta`、`DAG`、`PythonOperator`、`EmptyOperator`。
- 配置 `default_args`:`owner='data-team'`、`depends_on_past=False`、`email_on_failure=True`、`email_on_retry=False`、`retries=3`、`retry_delay=timedelta(minutes=5)`、`retry_exponential_backoff=True`、`max_retry_delay=timedelta(hours=1)`。
- 定义 DAG 参数:`dag_id='example_etl'`、`default_args=default_args`、`description='Example ETL pipeline'`、`schedule='0 6 * * *'`、`start_date=datetime(2024, 1, 1)`、`catchup=False`、`tags=['etl', 'example']`、`max_active_runs=1`。
- 创建 `start = EmptyOperator(task_id='start')`。
- 实现 `extract_data(**context)`:读取 `execution_date = context['ds']`,执行提取逻辑并返回如 `{'records': 1000}`。
- 创建 `extract = PythonOperator(task_id='extract', python_callable=extract_data)`。
- 创建 `end = EmptyOperator(task_id='end')`。
- 设置任务顺序:`start >> extract >> end`。
- 使用 TaskFlow API:让代码更简洁,并自动处理 XCom。
- 为任务设置 timeouts,防止出现 zombie tasks。
- 对 sensors 使用 `mode='reschedule'`,释放 worker 槽位。
- 为 DAG 编写单元测试和集成测试。
- 保证任务幂等,使其可安全重试。
- 不要使用 `depends_on_past=True`,避免产生瓶颈。
- 不要硬编码日期,使用 `{{ ds }}` 宏。
- 不要使用全局状态,任务应保持无状态。
- 不要盲目跳过 catchup,先理解其影响。
- 不要把重逻辑放在 DAG 文件中,从独立模块导入。
- 详细模式和工作示例在 `references/details.md`;当上面的导航层不够用时读取该文件。
适用边界 · 注意事项
- 未使用 Apache Airflow 的项目。
- 只需简单 cron 定时脚本、没有复杂依赖、重试、回溯或监控需求的场景。
- 无法部署 Airflow 调度器、Metadata DB 和 Executor 的环境。