二、Celery 任务优先级队列实现
2.1 任务队列基础配置
在 FastAPI 中集成 Celery 需要以下组件:
python
# requirements.txt
fastapi==0.89.1
celery==5.2.7
pydantic==1.10.4
redis==4.5.4
安装完成后进行基础配置:
python
# celery_config.py
from celery import Celery
celery_app = Celery(
'priority_app',
broker='redis://localhost:6379/0',
backend='redis://localhost:6379/1',
task_routes={
'high_priority': {'queue': 'high_priority'},
'low_priority': {'queue': 'low_priority'}
}
)
2.2 优先级队列实现原理
使用 RabbitMQ 作为 Broker 时的优先级配置:
python
# rabbitmq_config.py
celery_app.conf.update(
task_queue_max_priority=10,
task_default_priority=5
)
流程图展示任务处理流程:
graph TD
A[客户端请求] --> B{FastAPI路由}
B -->|高优先级| C[high_priority队列]
B -->|普通优先级| D[default队列]
C --> E[Worker优先处理]
D --> F[Worker空闲时处理]
2.3 实践案例:订单处理系统
使用 Pydantic 定义任务模型:
python
from pydantic import BaseModel
from typing import Optional
class OrderRequest(BaseModel):
order_id: str
priority: int = 5
items: list[str]
user_type: Optional[str] = 'regular'
定义带优先级的 Celery 任务:
python
@celery_app.task(bind=True, queue='high_priority')
async def process_order(self, order_data: dict):
from pydantic import ValidationError
try:
order = OrderRequest(**order_data)
if order.user_type == 'vip':
self.update_state(priority=0)
# 处理逻辑...
except ValidationError as e:
return {'status': 'error', 'details': e.errors()}
2.4 队列路由策略
在 FastAPI 路由中动态分配队列:
python
from fastapi import APIRouter
order_router = APIRouter()
@order_router.post("/orders")
async def create_order(order: OrderRequest):
if order.priority < 3:
queue_name = 'high_priority'
else:
queue_name = 'default'
process_order.apply_async(
kwargs={'order_data': order.dict()},
queue=queue_name,
priority=order.priority
)
return {"message": "Order received"}
课后 Quiz
- 当需要临时提升某个VIP用户的订单优先级时,应该修改任务中的哪个属性? A. task_name B. priority C. queue D. routing_key
正确答案:B 解析:通过修改任务的priority属性可以动态调整执行顺序,而不需要改变队列归属
常见报错处理
错误现象:任务未按预期优先级执行 可能原因:
- Broker 不支持优先级(如未配置 RabbitMQ)
- 未在 worker 启动时指定队列 解决方案:
bash
# 正确启动方式
celery -A celery_config worker -Q high_priority,low_priority -l info
预防建议:
- 使用支持优先级的消息代理(RabbitMQ)
- 在任务定义和调用时保持优先级数值范围一致
- 定期监控队列积压情况