‹
RabbitMQ(2)
# uv pip install aio-pika
# uvicorn RabbitMQFastAPI:app --reload
import asyncio
import os
from dotenv import load_dotenv
from contextlib import asynccontextmanager
from aio_pika import ExchangeType
from fastapi import FastAPI
import aio_pika
load_dotenv()
RABBIT_URL = os.getenv("RABBIT_URL", "amqp://guest:guest@localhost/")
connection = None
EXCHANGE_TYPES = {
"direct": ExchangeType.DIRECT,
"fanout": ExchangeType.FANOUT
}
async def init_rabbit():
"""建立 aio-pika 连接 (Robust 连接自动重连)"""
global connection
connection = await aio_pika.connect_robust(RABBIT_URL)
async def close_rabbit():
"""关闭连接"""
global connection
if connection and not connection.is_closed:
await connection.close()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期: 启动时建立连接, 关闭时释放连接"""
await init_rabbit()
yield # 作为分界线语法
await close_rabbit()
# 挂载 lifespan - 应用启动时候自动启动rabbit 应用关闭时自动关闭rabbit
app = FastAPI(lifespan=lifespan)
# ================= 生产者 =================
async def publish(queue: str, message: str, durable: bool = True):
"""发布消息到队列,delivery_mode=2 消息持久化"""
channel = await connection.channel()
await channel.declare_queue(queue, durable=durable) # 是否持久化到硬盘
await channel.default_exchange.publish(
"""包装标准化对象传输 - delivery_mode=2 表示落盘持久化"""
aio_pika.Message(body=message.encode("utf-8"), delivery_mode=2),
routing_key=queue
)
await channel.close()
async def publish_exchange(exchange: str, exchange_type: str, routing_key: str, message: str):
"""通过交换机发布消息,exchange_type 取值 direct / fanout"""
channel = await connection.channel()
ex = await channel.declare_exchange(
exchange,
type=EXCHANGE_TYPES.get(exchange_type, ExchangeType.DIRECT),
durable=True
)
await ex.publish(
aio_pika.Message(body=message.encode("utf-8"), delivery_mode=2),
routing_key=routing_key,
)
await channel.close()
# ================= 消费者 =================
async def consume(queue: str, handler, durable: bool = True):
"""消费队列:自动 ack + prefetch=1 公平分发"""
channel = await connection.channel()
await channel.set_qos(prefetch_count=1)
q = await channel.declare_queue(queue, durable=durable)
async with q.iterator() as queue_iter:
async for msg in queue_iter:
async with msg.process(): # 成功自动 ack, handler 异常自动 nack 重投
await handler(msg.body.decode("utf-8"))
# ================= 示例路由 =================
@app.post("/send")
async def send_message(queue: str, message: str):
"""POST /send?queue=demo&message=hello"""
await publish(queue, message)
return {"status": "ok", "queue": queue, "message": message}
@app.post("/publish")
async def publish_msg(exchange: str, exchange_type: str, routing_key: str, message: str):
"""POST /publish?exchange=logs&exchange_type=fanout&routing_key=&message=hello"""
await publish_exchange(exchange, exchange_type, routing_key, message)
return {"status": "ok", "exchange": exchange, "routing_key": routing_key}
# ================= 独立消费者脚本 (推荐, 与 Web 进程分离) =================
# 单独文件 consumer.py 里这样跑, 避免和请求抢事件循环:
# import asyncio
# from RabbitMQFastAPI import init_rabbit, close_rabbit, consume
#
# async def print_handler(msg):
# print("[收到]", msg)
#
# async def main():
# await init_rabbit()
# try:
# await consume("demo_queue", print_handler)
# finally:
# await close_rabbit()
#
# if __name__ == "__main__":
# asyncio.run(main())