[英]Making rabbitMQ connection globally
目前我有
async def send_rabbitmq(msg = {}):
connection = await connect("amqp://guest:guest@localhost/")
channel = await connection.channel()
await channel.default_exchange.publish(
Message(json.dumps(msg.dict()).encode("utf-8")),
routing_key = "fastapi_task"
)
await connection.close()
我想要做的是在全球范圍內建立連接,以便所有功能都可以訪問它
但是,當我刪除connection = await connect("amqp://guest:guest@localhost/")
並進行全局connection = connect("amqp://guest:guest@localhost/")
,我得到了AttributeError: 'coroutine' object has no attribute 'channel'
問題出在您的代碼中,當您使用 await 時,如果連接成功,則訪問通道的下一條語句將找到該對象。 connection = await connect("amqp://guest:guest@localhost/")
在第二個語句connection = connect("amqp://guest:guest@localhost/")
您沒有等待建立連接,這就是您收到打印錯誤的原因。
如果要使連接變量成為全局變量,請在函數外部聲明一個連接變量,並在函數內部使用global
關鍵字設置該變量。
內部函數:
global connection
connection = await connect("amqp://guest:guest@localhost/")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.