lanonna/lanonna/mq.py
2024-03-16 09:34:11 +01:00

30 lines
862 B
Python

import aio_pika
from collections import namedtuple
import protocol
import config
MQClient = namedtuple('MQClient', ('queue', 'exchange',
'connection', 'channel'))
async def initialize(c: config.Configuration):
connection = await aio_pika.connect_robust(c.mq_url)
channel = await connection.channel()
queue = await channel.declare_queue('lanonna')
exchange = await channel.declare_exchange('lanonna', durable=True)
await queue.bind(exchange)
return MQClient(queue, exchange, connection, channel)
async def route_to_exchange(rabbit_client: MQClient, msg: protocol.SwitchboardMessage):
import json
routing_key = msg.command
btes = json.dumps(msg._asdict()).encode()
mqmsg = aio_pika.Message(body=btes)
await rabbit_client.channel.default_exchange.publish(mqmsg, routing_key)