|
| 1 | +--- |
| 2 | +title: Broker |
| 3 | +--- |
| 4 | + |
| 5 | +To use broker with PostgreSQL you need to import broker and result backend from this library and provide a address for connection. For example, lets create a file `broker.py` with the following content: |
| 6 | + |
| 7 | +=== "asyncpg" |
| 8 | + |
| 9 | + ```python |
| 10 | + import asyncio |
| 11 | + from taskiq_pg.asyncpg import AsyncpgResultBackend, AsyncpgBroker |
| 12 | + |
| 13 | + |
| 14 | + dsn = "postgres://postgres:postgres@localhost:5432/postgres" |
| 15 | + broker = AsyncpgBroker(dsn).with_result_backend(AsyncpgResultBackend(dsn)) |
| 16 | + |
| 17 | + |
| 18 | + @broker.task |
| 19 | + async def best_task_ever() -> None: |
| 20 | + """Solve all problems in the world.""" |
| 21 | + await asyncio.sleep(5.5) |
| 22 | + print("All problems are solved!") |
| 23 | + |
| 24 | + |
| 25 | + async def main(): |
| 26 | + await broker.startup() |
| 27 | + task = await best_task_ever.kiq() |
| 28 | + print(await task.wait_result()) |
| 29 | + await broker.shutdown() |
| 30 | + |
| 31 | + |
| 32 | + if __name__ == "__main__": |
| 33 | + asyncio.run(main()) |
| 34 | + ``` |
| 35 | + |
| 36 | +=== "psqlpy" |
| 37 | + |
| 38 | + ```python |
| 39 | + import asyncio |
| 40 | + from taskiq_pg.psqlpy import PSQLPyResultBackend, PSQLPyBroker |
| 41 | + |
| 42 | + |
| 43 | + dsn = "postgres://postgres:postgres@localhost:5432/postgres" |
| 44 | + broker = PSQLPyBroker(dsn).with_result_backend(PSQLPyResultBackend(dsn)) |
| 45 | + |
| 46 | + |
| 47 | + @broker.task |
| 48 | + async def best_task_ever() -> None: |
| 49 | + """Solve all problems in the world.""" |
| 50 | + await asyncio.sleep(5.5) |
| 51 | + print("All problems are solved!") |
| 52 | + |
| 53 | + |
| 54 | + async def main(): |
| 55 | + await broker.startup() |
| 56 | + task = await best_task_ever.kiq() |
| 57 | + print(await task.wait_result()) |
| 58 | + await broker.shutdown() |
| 59 | + |
| 60 | + |
| 61 | + if __name__ == "__main__": |
| 62 | + asyncio.run(main()) |
| 63 | + ``` |
| 64 | + |
| 65 | +Then you can run this file with: |
| 66 | + |
| 67 | +```bash |
| 68 | +python broker.py |
| 69 | +``` |
0 commit comments