taskiq异步分布式任务管理器 适用fastapi

taskiq 异步分布式任务管理器

https://taskiq-python.github.io/

将 taskiq 视为 asyncio celery 实现。它使用几乎相同的模式,但它更加现代和灵活。

它不是任何其他任务管理器的直接替代品。它具有不同的库生态系统和一组不同的功能。此外,它不适用于同步项目。将无法同步发送任务。

1 安装taskiq

python 复制代码
pip install taskiq

2 使用

我这里使用的是fastapi+rabbitmq,所以需要多装一个taskiq-aio-pika包来使用

python 复制代码
pip install taskiq-aio-pika

项目路径如下:

broker.py:

python 复制代码
from taskiq_aio_pika import AioPikaBroker

from app.core.config import settings

broker = AioPikaBroker(url="amqp://guest:guest@localhost:5672//") # 此处替换broker_url

这里必须要定义一个worker.py,显式的导入你的tasks和broker。不然会报如下错误:

python 复制代码
task "xxxx" is not found. Maybe you forgot to import it?

worker.py:

python 复制代码
from app.tasks.broker import broker

import app.tasks.notify_tasks

xxx_tasks.py:

python 复制代码
from app.tasks.broker import broker


@broker.task
async def test_tasks():
	# 现在就可以支持async await使用 例如:
	async with httpx.AsyncClient() as client:
		await client.post("jd.com", json=body)
	return 

3 cli启动命令:

python 复制代码
taskiq worker app.tasks.worker:broker