aio-pika的使用

来自:https://www.cnblogs.com/Cpsyche/p/14794013.html

生产者
创建连接
生成channel
声明队列
无回调函数
import asyncio
import aio_pika

async def main():
connection = await aio_pika.connect_robust(
“amqp://guest:guest@127.0.0.1/”
)
# 建立连接

queue_name = "test_queue"
async with connection:
    # 上下文管理,退出时自动关闭connection
    channel = await connection.channel()
    # 创建channel
    # Declaring queue
    queue = await channel.declare_queue(queue_name, auto_delete=True)
    # auto_delete 通道关闭时是否删除队列
    # 声明队列
    async with queue.iterator() as queue_iter:
        async for message in queue_iter:
            async with message.process():
                print(message.body)
                # 获取消息

if name == “main”:
asyncio.run(main())

有回调函数
import asyncio
from aio_pika import connect, IncomingMessage

async def on_message(message: IncomingMessage):
“”"
on_message doesn’t necessarily have to be defined as async.
Here it is to show that it’s possible.
“”"

print("Message body is: %r" % message.body)
await asyncio.sleep(5)  # Represents async I/O operations

async def main(loop):
# Perform connection
connection = await connect(
“amqp://guest:guest@localhost/”, loop=loop
)

# Creating a channel
channel = await connection.channel()

# Declaring queue
queue = await channel.declare_queue("hello")

# Start listening the queue with name 'hello'
await queue.consume(on_message, no_ack=True)

if name == “main”:
loop = asyncio.get_event_loop()
loop.create_task(main(loop))
loop.run_forever()

消费者
创建连接
生成channel
声明队列,避免队列不存在
通过队列向channel发送消息
import asyncio
import aio_pika

async def main():
connection = await aio_pika.connect_robust(
“amqp://guest:guest@127.0.0.1/”
)
# 生成连接

async with connection:
    routing_key = "test_queue"
    channel = await connection.channel()
    # 生成通道

    queue = await channel.declare_queue(routing_key, auto_delete=True)
    # 声明队列信息,避免队列不存在

    await channel.default_exchange.publish(
        aio_pika.Message(body="Hello {}".format(routing_key).encode()),
        routing_key=routing_key,
    )
    # 向指定队列发布消息

if name == “main”:
asyncio.run(main())

FANOUT(分发订阅模式)
生产者
创建连接
生成channel
声明交换机,类型为FANOUT
交换机直接发布消息,routing_key为空
import asyncio
from aio_pika import connect, Message, DeliveryMode, ExchangeType

async def main():
# Perform connection
connection = await connect(
“amqp://guest:guest@localhost/”
)
# 生成连接

# Creating a channel
channel = await connection.channel()
# 创建通道

logs_exchange = await channel.declare_exchange(
    "logs", ExchangeType.FANOUT
)
# 绑定交换机,发布订阅模式

message_body = b"Hello World!"

message = Message(
    message_body,
    delivery_mode=DeliveryMode.PERSISTENT
)
# delivery_mode消息是否持久化

await logs_exchange.publish(message, routing_key="")
# 交换机绑定队列发布消息,不用声明队列

await connection.close()
# 确保信息到达

if name == “main”:
asyncio.run(main())

消费者
创建连接
生成channel
声明交换机
声明队列参数为exclusive=True
队列绑定交换机,routing_key为空等待接收消息
import asyncio
from aio_pika import connect, IncomingMessage, ExchangeType

async def main():
# Perform connection
connection = await connect(
“amqp://guest:guest@localhost/”
)

# Creating a channel
channel = await connection.channel()
await channel.set_qos(prefetch_count=1)

logs_exchange = await channel.declare_exchange(
    "logs", ExchangeType.FANOUT
)

# Declaring queue
queue = await channel.declare_queue(exclusive=True)

# Binding the queue to the exchange
await queue.bind(logs_exchange)

async with queue.iterator() as queue_iter:
    async for message in queue_iter:
        async with message.process():
            print(message.body)

if name == “main”:
asyncio.run(main())

direct(路由模式)
生产者
创建连接
生成channel
声明交换机,类型为direct
交换机直接发布消息,设置routing_key
import asyncio
from aio_pika import connect, Message, DeliveryMode, ExchangeType

async def main():
# Perform connection
connection = await connect(
“amqp://guest:guest@localhost/”
)

# Creating a channel
channel = await connection.channel()

logs_exchange = await channel.declare_exchange(
    "logss", ExchangeType.DIRECT
)

message_body = b"Hello World!"

message = Message(
    message_body,
    delivery_mode=DeliveryMode.PERSISTENT
)

# Sending the message
routing_key = "info"
await logs_exchange.publish(message, routing_key=routing_key)

await connection.close()

if name == “main”:
asyncio.run(main())

消费者
创建连接
生成channel
声明交换机,类型为direct
队列绑定交换机,,设置routing_key
等待接收消息
import asyncio
from aio_pika import connect, IncomingMessage, ExchangeType

async def main():
# Perform connection
connection = await connect(
“amqp://guest:guest@localhost/”
)

# Creating a channel
channel = await connection.channel()

direct_logs_exchange = await channel.declare_exchange(
    "logss", ExchangeType.DIRECT
)

# Declaring random queue
queue = await channel.declare_queue(durable=True)

severity = "info"

await queue.bind(direct_logs_exchange, routing_key=severity)

async with queue.iterator() as queue_iter:
    async for message in queue_iter:
        async with message.process():
            print(message.body)

if name == “main”:
asyncio.run(main())

交换机会向routing_key相同的队列中发送数据

topic(主题模式)
创建连接
生成channel
声明交换机,类型为topic
交换机直接发布消息,设置routing_key

import asyncio
from aio_pika import connect, Message, DeliveryMode, ExchangeType

async def main():
# Perform connection
connection = await connect(
“amqp://guest:guest@localhost/”
)

# Creating a channel
channel = await connection.channel()

logs_exchange = await channel.declare_exchange(
    "log2", ExchangeType.TOPIC
)

message_body = b"Hello World!"

message = Message(
    message_body,
    delivery_mode=DeliveryMode.PERSISTENT
)

# Sending the message
routing_key = "xxx.info"
await logs_exchange.publish(message, routing_key=routing_key)

await connection.close()

if name == “main”:
asyncio.run(main())

消费者
创建连接
生成channel
声明交换机,类型为direct
队列绑定交换机,,设置routing_key
等待接收消息
import sys
import asyncio
from aio_pika import connect, IncomingMessage, ExchangeType

async def main():
# Perform connection
connection = await connect(
“amqp://guest:guest@localhost/”
)

# Creating a channel
channel = await connection.channel()

direct_logs_exchange = await channel.declare_exchange(
    "log2", ExchangeType.TOPIC
)

# Declaring random queue
queue = await channel.declare_queue(durable=True)

severity = "#.info"

await queue.bind(direct_logs_exchange, routing_key=severity)

async with queue.iterator() as queue_iter:
    async for message in queue_iter:
        async with message.process():
            print(message.body)

if name == “main”:
asyncio.run(main())

topics模式中要注意,三种符号

符号 作用
. 用来分割单词

  • 匹配一个单词

匹配一个或多个单词

生产者用完整的routing_key,消费者用*或#进行模糊匹配

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值