|
1 | 1 | import asyncio
|
| 2 | +import sys |
2 | 3 |
|
3 | 4 | from aio_pika import ExchangeType, connect
|
4 | 5 | from aio_pika.abc import AbstractIncomingMessage
|
5 | 6 |
|
6 | 7 |
|
7 |
| -async def on_message(message: AbstractIncomingMessage) -> None: |
8 |
| - async with message.process(): |
9 |
| - print(f"[x] {message.body!r}") |
10 |
| - |
11 |
| - |
12 | 8 | async def main() -> None:
|
13 | 9 | # Perform connection
|
14 | 10 | connection = await connect("amqp://guest:guest@localhost/")
|
15 | 11 |
|
16 |
| - async with connection: |
17 |
| - # Creating a channel |
18 |
| - channel = await connection.channel() |
19 |
| - await channel.set_qos(prefetch_count=1) |
| 12 | + channel = await connection.channel() |
| 13 | + await channel.set_qos(prefetch_count=1) |
| 14 | + |
| 15 | + topic_logs_exchange = await channel.declare_exchange( |
| 16 | + "topic_logs", |
| 17 | + ExchangeType.TOPIC, |
| 18 | + ) |
| 19 | + |
| 20 | + queue = await channel.declare_queue( |
| 21 | + "task_queue", |
| 22 | + durable=True, |
| 23 | + ) |
20 | 24 |
|
21 |
| - logs_exchange = await channel.declare_exchange( |
22 |
| - "logs", |
23 |
| - ExchangeType.FANOUT, |
24 |
| - ) |
| 25 | + binding_keys = sys.argv[1:] |
25 | 26 |
|
26 |
| - # Declaring queue |
27 |
| - queue = await channel.declare_queue(exclusive=True) |
| 27 | + if not binding_keys: |
| 28 | + sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0]) |
| 29 | + sys.exit(1) |
28 | 30 |
|
29 |
| - # Binding the queue to the exchange |
30 |
| - await queue.bind(logs_exchange) |
| 31 | + for binding_key in binding_keys: |
| 32 | + await queue.bind(topic_logs_exchange, routing_key=binding_key) |
31 | 33 |
|
32 |
| - # Start listening the queue |
33 |
| - await queue.consume(on_message) |
| 34 | + print(" [*] Waiting for messages. To exit press CTRL+C") |
34 | 35 |
|
35 |
| - print(" [*] Waiting for logs. To exit press CTRL+C") |
36 |
| - await asyncio.Future() |
| 36 | + async with queue.iterator() as iterator: |
| 37 | + message: AbstractIncomingMessage |
| 38 | + async for message in iterator: |
| 39 | + async with message.process(): |
| 40 | + print(f" [x] {message.routing_key!r}:{message.body!r}") |
37 | 41 |
|
38 | 42 |
|
39 | 43 | if __name__ == "__main__":
|
|
0 commit comments