HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

06-测试和Celery(Testing & Celery)

第 30 / 45 段:Celery(异步任务)

Django 风格指南 (HackSoft) · 发布 2026-02-05 · 更新 2026-11-11 · 标签:Django、测试、Celery、异步任务

Celery(异步任务)(续)

@shared_task(
    bind=True,
    autoretry_for=(ConnectionError, TimeoutError),  # 自动重试这些异常
    retry_kwargs={'max_retries': 5},  # 最多重试 5 次
    retry_backoff=True,  # 使用指数退避
    retry_backoff_max=600,  # 最大退避时间 10 分钟
    retry_jitter=True,  # 添加随机抖动
)
def send_notification(self, user_id, message):
    """
    发送通知,带高级重试机制
    """
    user = User.objects.get(id=user_id)

    from notifications.services import notification_send

    try:
        notification_send(user=user, message=message)
    except RateLimitError as exc:
        # 遇到限流错误,等待更长时间再重试
        raise self.retry(exc=exc, countdown=60 * 5)  # 5 分钟后重试

配置

我们基本上遵循官方指南,将 Celery 与 Django 集成:

完整示例

查看 Django-Styleguide-Example 项目中的 Celery 配置: