【发布时间】:2021-01-28 15:27:00
【问题描述】:
我正在尝试将我的 websocket 端点与 rabbitmq (aio-pika) 挂钩。目标是让该端点中的侦听器和来自队列的任何新消息通过 websockets 将消息传递给浏览器客户端。
我在带有 asyncio 循环的脚本中使用 asyncio 测试了消费者。按照我的方式工作并使用 aio-pika 文档。 (来源:https://aio-pika.readthedocs.io/en/latest/rabbitmq-tutorial/2-work-queues.html,worker.py)
但是,当我在 websockets 端点的 fastapi 中使用它时,我无法使其工作。不知何故,听众:
await queue.consume(on_message)
被完全忽略。
这是我的尝试(我把它全部放在一个函数中,所以它更具可读性):
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
print("Entering websockets")
await manager.connect(websocket)
print("got connection")
# params
queue_name = "task_events"
routing_key = "user_id.task"
con = "amqp://rabbitmq:rabbitmq@rabbit:5672/"
connection = await connect(con)
channel = await connection.channel()
await channel.set_qos(prefetch_count=1)
exchange = await channel.declare_exchange(
"topic_logs",
ExchangeType.TOPIC,
)
# Declaring queue
queue = await channel.declare_queue(queue_name)
# Binding the queue to the exchange
await queue.bind(exchange, routing_key)
async def on_message(message: IncomingMessage):
async with message.process():
# here will be the message passed over websockets to browser client
print("sent", message.body)
try:
######### Not working as expected ###########
# await does not await and websockets finishes, as there is no loop
await queue.consume(on_message)
#############################################
################ This Alternative code atleast receives some messages #############
# If I use this part, I atleast get some messages, when I trigger a backend task that publishes new messages to the queue.
# It seems like the messages are somehow stuck and new task releases all stucked messages, but does not release new one.
while True:
await queue.consume(on_message)
await asyncio.sleep(1)
################## one part #############
except WebSocketDisconnect:
manager.disconnect(websocket)
我对 python 中的异步非常陌生。我不确定问题出在哪里,在从 aio-pika 获得 worker.py 的启发时,我无法以某种方式实现异步消耗循环。
【问题讨论】:
标签: websocket async-await rabbitmq python-asyncio fastapi