• aio-pika的使用


    aio-pika的使用

    简单使用

    生产者

    1. 创建连接
    2. 生成channel
    3. 声明队列

    无回调函数

    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()
    

    消费者

    1. 创建连接
    2. 生成channel
    3. 声明队列,避免队列不存在
    4. 通过队列向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(分发订阅模式)

    生产者

    1. 创建连接
    2. 生成channel
    3. 声明交换机,类型为FANOUT
    4. 交换机直接发布消息,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())
    

    消费者

    1. 创建连接
    2. 生成channel
    3. 声明交换机
    4. 声明队列参数为exclusive=True
    5. 队列绑定交换机,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(路由模式)

    生产者

    1. 创建连接
    2. 生成channel
    3. 声明交换机,类型为direct
    4. 交换机直接发布消息,设置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())
    
    

    消费者

    1. 创建连接
    2. 生成channel
    3. 声明交换机,类型为direct
    4. 队列绑定交换机,,设置routing_key
    5. 等待接收消息
    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(主题模式)

    1. 创建连接
    2. 生成channel
    3. 声明交换机,类型为topic
    4. 交换机直接发布消息,设置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())
    
    

    消费者

    1. 创建连接
    2. 生成channel
    3. 声明交换机,类型为direct
    4. 队列绑定交换机,,设置routing_key
    5. 等待接收消息
    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,消费者用*或#进行模糊匹配

  • 相关阅读:
    腾讯一面有感(移动开发岗位)
    kafka 在java中的使用
    Kafka史上最详细原理总结下
    java jdk原生的http请求工具类
    kafka(一)
    MySQL:互联网公司常用分库分表方案汇总
    密码正则
    springboot 打war包
    oracle存储过程的一些使用
    对象的深度克隆
  • 原文地址:https://www.cnblogs.com/Cpsyche/p/14794013.html
Copyright © 2020-2023  润新知