Async RabbitMQ worker utilities
Project description
WorkerLib - асинхронная работа с RabbitMQ
Быстрый старт
import asyncio
from workerlib import WorkerPool
async def task_handler(data: dict) -> bool:
print(f"Обработка: {data}")
return True
async def main():
async with WorkerPool() as pool:
pool.add_worker("tasks", task_handler)
await pool.send("tasks", {"id": 1, "cmd": "start"})
await asyncio.sleep(2)
asyncio.run(main())
Формат сообщений
JSON сообщение Библиотека автоматически сериализует dict в JSON при отправке:
# Отправка простого сообщения
await pool.send("queue", {
"event": "user_created",
"user_id": 123,
"email": "user@example.com",
"timestamp": "2024-01-15T10:30:00Z"
})
# Отправка вложенных структур
await pool.send("queue", {
"type": "order",
"data": {
"order_id": "ORD-12345",
"items": [
{"id": 1, "quantity": 2},
{"id": 2, "quantity": 1}
],
"total": 299.99
},
"metadata": {
"source": "api",
"version": "1.0"
}
})
Основные примеры
- Пул с несколькими воркерами
from workerlib import WorkerPool, ErrorHandlingStrategy
async def main():
async with WorkerPool() as pool:
# Email воркер с DLQ
pool.add_worker(
queue_name="emails",
handler=email_handler,
error_strategy=ErrorHandlingStrategy.DLQ,
prefetch_count=5
)
# Обработчик платежей
pool.add_worker(
queue_name="payments",
handler=payment_handler,
error_strategy=ErrorHandlingStrategy.REQUEUE_END
)
# Отправка задач
await pool.send("emails", {"to": "user@test.com"})
await pool.send("payments", {"amount": 100})
- Кастомное подключение и retry
from workerlib import ConnectionParams, RetryConfig
params = ConnectionParams(
host="rabbit.local",
username="admin",
password="secret"
)
retry_config = RetryConfig(
max_attempts=3,
initial_delay=1.0,
backoff_factor=2.0
)
async with WorkerPool(connection_params=params) as pool:
pool.add_worker(
queue_name="critical",
handler=critical_handler,
retry_config=retry_config
)
- Обработка ошибок
from workerlib import ErrorHandlingStrategy
# Варианты:
# IGNORE - проигнорировать ошибку
# REQUEUE_END - в конец очереди с задержкой
# REQUEUE_FRONT - в начало очереди
# DLQ - в Dead Letter Queue
pool.add_worker(
queue_name="tasks",
handler=my_handler,
error_strategy=ErrorHandlingStrategy.DLQ,
dlq_enabled=True,
requeue_delay=5.0 # задержка повторной обработки
)
- Отдельные компоненты
from workerlib import (
RabbitMQConnection,
RabbitMQQueue,
RabbitMQConsumer,
RabbitMQProducer
)
# Создание вручную
connection = RabbitMQConnection()
await connection.connect()
queue = RabbitMQQueue(connection, QueueConfig(name="my_queue"))
producer = RabbitMQProducer(connection, queue)
await producer.send({"test": "data"})
consumer = RabbitMQConsumer(queue, my_handler)
await consumer.consume()
- Batch отправка
async with WorkerPool() as pool:
messages = [
{"id": i, "data": f"item_{i}"}
for i in range(100)
]
tasks = [
pool.send("batch_queue", msg)
for msg in messages
]
await asyncio.gather(*tasks)
- Метрики
async with WorkerPool() as pool:
pool.add_worker("monitored", handler)
# Отправляем задачи
for i in range(10):
await pool.send("monitored", {"task": i})
# Получаем метрики
metrics = pool.get_metrics("monitored")
print(f"Обработано: {metrics['consumer']['processed']}")
print(f"Ошибок: {metrics['consumer']['failed']}")
- FastAPI интеграция
from fastapi import FastAPI
from workerlib import WorkerPool
app = FastAPI()
worker_pool = WorkerPool(auto_start=False)
@app.on_event("startup")
async def startup():
await worker_pool.start()
worker_pool.add_worker("api_tasks", task_handler)
@app.on_event("shutdown")
async def shutdown():
await worker_pool.stop()
@app.post("/task")
async def create_task(data: dict):
await worker_pool.send("api_tasks", data)
return {"status": "queued"}
Конфигурация
ConnectionParams
ConnectionParams(
host="127.0.0.1",
port=5672,
username="guest",
password="guest",
heartbeat=60,
timeout=10
)
QueueConfig
QueueConfig(
name="queue_name",
durable=True,
prefetch_count=1
)
RetryConfig
RetryConfig(
max_attempts=3,
initial_delay=1.0,
backoff_factor=2.0,
max_delay=60.0
)
Установка
pip install workerlib
Требования: Python 3.8+, aio_pika
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file workerlib-0.4.0.tar.gz.
File metadata
- Download URL: workerlib-0.4.0.tar.gz
- Upload date:
- Size: 15.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5f16f4130e7be46fb8ef343eec63302745a28a97700117a3b48628d6ce0fc840
|
|
| MD5 |
ac28430fc7a5a1db5579b6bb44b82b2c
|
|
| BLAKE2b-256 |
6c40cefe9a07d694865b48341242af47bf2c4a69ad6d705ffc5dd2080b5162be
|
Provenance
The following attestation bundles were made for workerlib-0.4.0.tar.gz:
Publisher:
publish.yml on ametist-dev/workerlib
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
workerlib-0.4.0.tar.gz -
Subject digest:
5f16f4130e7be46fb8ef343eec63302745a28a97700117a3b48628d6ce0fc840 - Sigstore transparency entry: 868449690
- Sigstore integration time:
-
Permalink:
ametist-dev/workerlib@cfe8a72dcc1738d4d36552a32a2b07ef5d2d060a -
Branch / Tag:
refs/tags/0.4.0 - Owner: https://github.com/ametist-dev
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@cfe8a72dcc1738d4d36552a32a2b07ef5d2d060a -
Trigger Event:
release
-
Statement type:
File details
Details for the file workerlib-0.4.0-py3-none-any.whl.
File metadata
- Download URL: workerlib-0.4.0-py3-none-any.whl
- Upload date:
- Size: 11.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7a648b95aac0b5fc512a1ad8edd05642f7bdc682f6bde0f72b47e59fc0e88797
|
|
| MD5 |
dc1c270fec80a5aeab895fd0f7cde0fb
|
|
| BLAKE2b-256 |
341665afd3bbc1b294ca3e3e229769cc890e20f267e99d42a7b018bbf2e54cda
|
Provenance
The following attestation bundles were made for workerlib-0.4.0-py3-none-any.whl:
Publisher:
publish.yml on ametist-dev/workerlib
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
workerlib-0.4.0-py3-none-any.whl -
Subject digest:
7a648b95aac0b5fc512a1ad8edd05642f7bdc682f6bde0f72b47e59fc0e88797 - Sigstore transparency entry: 868449694
- Sigstore integration time:
-
Permalink:
ametist-dev/workerlib@cfe8a72dcc1738d4d36552a32a2b07ef5d2d060a -
Branch / Tag:
refs/tags/0.4.0 - Owner: https://github.com/ametist-dev
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@cfe8a72dcc1738d4d36552a32a2b07ef5d2d060a -
Trigger Event:
release
-
Statement type: