📊 Capítulo 14: Filas com Celery & Redis
Especialização Backend com Python & FastAPI
🗺️ A Arquitetura de Processamento Assíncrono com Celery
flowchart LR
API["FastAPI API Server (Producer)"]
--> |"delay() / apply_async()"| BROKER["Message Broker (Redis / RabbitMQ)"]
BROKER --> |"Distribuição de Tasks"| WORKERS["Celery Workers (Processos Dedicados em Background)"]
WORKERS --> RESULT_BACKEND["Result Backend (Redis / PostgreSQL)"]
WORKERS --> FLOWER["Monitoramento Flower Dashboard"]
style API fill:#ede7f6,stroke:#512da8,stroke-width:2px
style BROKER fill:#fff3e0,stroke:#ff9800,stroke-width:2px
style WORKERS fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
style RESULT_BACKEND fill:#e1f5fe,stroke:#03a9f4,stroke-width:1.5px
style FLOWER fill:#c8e6c9,stroke:#2e7d32,stroke-width:1.5px
🎯 Slide 1: Definindo Tarefas Celery com @celery_app.task
# app/core/celery_app.py
from celery import Celery
celery_app = Celery(
"worker",
broker="redis://localhost:6379/0",
backend="redis://localhost:6379/1"
)
@celery_app.task(bind=True, max_retries=3, default_retry_delay=60)
def processar_relatorio_pesado(self, usuario_id: int, ano: int):
try:
gerar_pdf_complexo(usuario_id, ano)
except Exception as exc:
raise self.retry(exc=exc)
🎯 Slide 2: Disparando Tarefas pelo FastAPI
@router.post("/relatorios/anual")
async def solicitar_relatorio(ano: int, user: Usuario = Depends(get_current_user)):
task = processar_relatorio_pesado.delay(user.id, ano)
return {
"status": "Processamento iniciado",
"task_id": task.id,
"consulta_status_url": f"/api/v1/tasks/{task.id}"
}
🎯 Slide 3: Celery Beat (Tarefas Periódicas e Cron Jobs)
-
Automação Contínua: Permite agendar tarefas para rodar em intervalos fixos (ex.: todo dia à meia-noite, a cada 5 minutos).
- Flower Dashboard: Interface web em tempo real para inspecionar workers ativos, filas, taxas de erro e consumo de memória.
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim