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 配置: