Python RabbitMQ Demo

fanout消息订阅模式

  • 生产者

    # 生产者代码
    import pika
    
    
    credentials = pika.PlainCredentials('guest', 'guest')  # mq用户名和密码
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',
                                                                   credentials=credentials))
    # 建立rabbit协议的通道
    channel = connection.channel()
    # fanout: 所有绑定到此exchange的queue都可以接收消息(实时广播)
    # direct: 通过routingKey和exchange决定的那一组的queue可以接收消息(有选择接受)
    # topic: 所有符合routingKey(此时可以是一个表达式)的routingKey所bind的queue可以接收消息(更细致的过滤)
    channel.exchange_declare('logs', exchange_type='fanout')
    
    
    #因为是fanout广播类型的exchange,这里无需指定routing_key
    for i in range(10):
        channel.basic_publish(exchange='logs',
                              routing_key='',
                              body='Hello world!%s' % i)
    
    # 关闭与rabbitmq server的连接
    connection.close()
    
  • 消费者

    import pika
    
    credentials = pika.PlainCredentials('guest', 'guest')
    # BlockingConnection:同步模式
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',
                                                                   credentials=credentials))
    channel = connection.channel()
    
    #作为好的习惯,在producer和consumer中分别声明一次以保证所要使用的exchange存在
    channel.exchange_declare(exchange='logs',
                             exchange_type='fanout')
    
    # 随机生成一个新的空的queue,将exclusive置为True,这样在consumer从RabbitMQ断开后会删除该queue
    # 是排他的。
    result = channel.queue_declare('', exclusive=True)
    
    # 用于获取临时queue的name
    queue_name = result.method.queue
    
    # exchange与queue之间的关系成为binding
    # binding告诉exchange将message发送该哪些queue
    channel.queue_bind(exchange='logs',
                       queue=queue_name)
    
    # 定义一个回调函数来处理消息队列中的消息,这里是打印出来
    def callback(ch, method, properties, body):
        # 手动发送确认消息
        print(body.decode())
        # 告诉生产者,消费者已收到消息
        #ch.basic_ack(delivery_tag=method.delivery_tag)
    
    # 如果该消费者的channel上未确认的消息数达到了prefetch_count数,则不向该消费者发送消息
    channel.basic_qos(prefetch_count=1)
    # 告诉rabbitmq,用callback来接收消息
    # 默认情况下是要对消息进行确认的,以防止消息丢失。
    # 此处将no_ack明确指明为True,不对消息进行确认。
    channel.basic_consume(queue=queue_name,
                          on_message_callback=callback,
                          auto_ack=True)  # 自动发送确认消息
    # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
    channel.start_consuming()
    

rabbitmq延迟队列

  • MQ类

    """
    Created on Fri Aug  3 17:00:44 2018
    
    """
    import pika,json,logging
    class RabbitMQClient:
        def __init__(self, conn_str='amqp://guest:guest@127.0.0.1/%2f'):
            self.exchange_type = "direct"
            self.connection_string = conn_str
            self.connection = pika.BlockingConnection(pika.URLParameters(self.connection_string))
            self.channel = self.connection.channel()
            self._declare_retry_queue() #RetryQueue and RetryExchange
            logging.debug("connection established")
        def close_connection(self):
            self.connection.close()
            logging.debug("connection closed")
        def declare_exchange(self, exchange):
            self.channel.exchange_declare(exchange=exchange,
                                          exchange_type=self.exchange_type,
                                          durable=True)
        def declare_queue(self, queue):
            self.channel.queue_declare(queue=queue,
                                       durable=True,)
        def declare_delay_queue(self, queue,DLX='RetryExchange',TTL=60000):
            """
            创建延迟队列
            :param TTL: ttl的单位是us,ttl=60000 表示 60s
            :param queue:
            :param DLX:死信转发的exchange
            :return:
            """
            arguments={}
            if DLX:
                #设置死信转发的exchange
                arguments[ 'x-dead-letter-exchange']=DLX
            if TTL:
                arguments['x-message-ttl']=TTL
            print(arguments)
            self.channel.queue_declare(queue=queue,
                                       durable=True,
                                       arguments=arguments)
        def _declare_retry_queue(self):
            """
            创建异常交换器和队列,用于存放没有正常处理的消息。
            :return:
            """
            self.channel.exchange_declare(exchange='RetryExchange',
                                          exchange_type='fanout',
                                          durable=True)
            self.channel.queue_declare(queue='RetryQueue',
                                       durable=True)
            self.channel.queue_bind('RetryQueue', 'RetryExchange','RetryQueue')
        def publish_message(self,routing_key, msg,exchange='',delay=0,TTL=None):
            """
            发送消息到指定的交换器
            :param exchange: RabbitMQ交换器
            :param msg: 消息实体,是一个序列化的JSON字符串
            :return:
            """
            if delay==0:
                self.declare_queue(routing_key)
            else:
                self.declare_delay_queue(routing_key,TTL=TTL)
            if exchange!='':
                self.declare_exchange(exchange)
            self.channel.basic_publish(exchange=exchange,
                                       routing_key=routing_key,
                                       body=msg,
                                       properties=pika.BasicProperties(
                                           delivery_mode=2,
                                           type=exchange
                                       ))
            self.close_connection()
            print("message send out to %s" % exchange)
            logging.debug("message send out to %s" % exchange)
        def start_consume(self,callback,queue='#',delay=1):
            """
            启动消费者,开始消费RabbitMQ中的消息
            :return:
            """
            if delay==1:
                queue='RetryQueue'
            else:
                self.declare_queue(queue)
            self.channel.basic_qos(prefetch_count=1)
            try:
                self.channel.basic_consume(  # 消费消息
                    queue,  # 你要从那个队列里收消息
                    callback,  # 如果收到消息,就调用callback函数来处理消息
                )
                self.channel.start_consuming()
            except KeyboardInterrupt:
                self.stop_consuming()
        def stop_consuming(self):
            self.channel.stop_consuming()
            self.close_connection()
        def message_handle_successfully(channel, method):
            """
            如果消息处理正常完成,必须调用此方法,
            否则RabbitMQ会认为消息处理不成功,重新将消息放回待执行队列中
            :param channel: 回调函数的channel参数
            :param method: 回调函数的method参数
            :return:
            """
            channel.basic_ack(delivery_tag=method.delivery_tag)
        def message_handle_failed(channel, method):
            """
            如果消息处理失败,应该调用此方法,会自动将消息放入异常队列
            :param channel: 回调函数的channel参数
            :param method: 回调函数的method参数
            :return:
            """
            channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
    
    
  • 生产者

    from rabbitmq_demo import RabbitMQClient
    print("start program")
    client = RabbitMQClient()
    msg1 = '{"key":"10秒钟后执行"}'
    client.publish_message('test-delay',msg1,delay=1,TTL=10000)
    print("message send out")
    
  • 消费者

    from rabbitmq_demo import RabbitMQClient
    import json
    print("start program")
    client = RabbitMQClient()
    def callback(ch, method, properties, body):
        msg = body.decode()
        print(msg)
        # 如果处理成功,则调用此消息回复ack,表示消息成功处理完成。
        RabbitMQClient.message_handle_successfully(ch, method)
    queue_name = "RetryQueue"
    client.start_consume(callback,queue_name,delay=0)
    
    

RPC远程过程调用

  • 生产者

    # 生产者代码
    import pika
    import uuid
    
    
    # 在一个类中封装了connection建立、queue声明、consumer配置、回调函数等
    class FibonacciRpcClient(object):
        def __init__(self):
            # 建立到RabbitMQ Server的connection
            self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', credentials=pika.PlainCredentials('guest', 'guest')))
    
            self.channel = self.connection.channel()
    
            # 声明一个临时的回调队列
            result = self.channel.queue_declare('', exclusive=True)
            self._queue = result.method.queue
    
            # 此处client既是producer又是consumer,因此要配置consume参数
            # 这里的指明从client自己创建的临时队列中接收消息
            # 并使用on_response函数处理消息
            # 不对消息进行确认
            self.channel.basic_consume(queue=self._queue,
                                       on_message_callback=self.on_response,
                                       auto_ack=True)
            self.response = None
            self.corr_id = None
    
        # 定义回调函数
        # 比较类的corr_id属性与props中corr_id属性的值
        # 若相同则response属性为接收到的message
        def on_response(self, ch, method, props, body):
            print(body)
            if self.corr_id == props.correlation_id:
                print(body, '----')
                self.response = body
    
        def call(self, n):
            # 初始化response和corr_id属性
            self.corr_id = str(uuid.uuid4())
    
            # 使用默认exchange向server中定义的rpc_queue发送消息
            # 在properties中指定replay_to属性和correlation_id属性用于告知远程server
            # correlation_id属性用于匹配request和response
            self.channel.basic_publish(exchange='',
                                       routing_key='rpc_queue',
                                       properties=pika.BasicProperties(
                                           reply_to=self._queue,
                                           correlation_id=self.corr_id,
                                       ),
                                       # message需为字符串
                                       body=str(n))
    
            while self.response is None:
                self.connection.process_data_events()
    
            return int(self.response)
    
    
    # 生成类的实例
    fibonacci_rpc = FibonacciRpcClient()
    
    print(" [x] Requesting fib(30)")
    # 调用实例的call方法
    response = fibonacci_rpc.call(31)
    print(" [.] Got %r" % response)
    
  • 消费者

    # 消费者代码,这里以生成斐波那契数列为例
    import pika
    
    # 建立到达RabbitMQ Server的connection
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', credentials=pika.PlainCredentials('guest', 'guest')))
    channel = connection.channel()
    
    # 声明一个名为rpc_queue的queue
    channel.queue_declare(queue='rpc_queue')
    
    # 计算指定数字的斐波那契数
    def fib(n):
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            return fib(n - 1) + fib(n - 2)
    
    # 回调函数,从queue接收到message后调用该函数进行处理
    def on_request(ch, method, props, body):
        # 由message获取要计算斐波那契数的数字
        n = int(body)
        print(" [.] fib(%s)" % n)
        # 调用fib函数获得计算结果
    
    channel.basic_consume(queue='',
                          on_message_callback=on_request,
                          auto_ack=True)
    
    channel.start_consuming()
    

单生产者消费者模型

  • 生产者

    # 生产者代码
    import pika
    
    
    credentials = pika.PlainCredentials("guest","guest")  # mq用户名和密码,没有则需要自己创建
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    connection = pika.BlockingConnection(pika.ConnectionParameters(host="127.0.0.1",
                                                                   credentials=credentials))
    
    # 建立rabbit协议的通道
    channel = connection.channel()
    # 声明消息队列,消息将在这个队列传递,如不存在,则创建。durable指定队列是否持久化
    channel.queue_declare(queue='python-test', durable=False)
    
    # message不能直接发送给queue,需经exchange到达queue,此处使用以空字符串标识的默认的exchange
    # 向队列插入数值 routing_key是队列名
    channel.basic_publish(exchange='',
                          routing_key='python-test',
                          body='Hello wo5555555')
    # 关闭与rabbitmq server的连接
    connection.close()
    
  • 消费者

    # 消费者代码
    import pika
    
    credentials = pika.PlainCredentials("guest","guest")
    # BlockingConnection:同步模式
    connection = pika.BlockingConnection(pika.ConnectionParameters(host="127.0.0.1",
                                                                credentials=credentials))
    channel = connection.channel()
    # 申明消息队列。当不确定生产者和消费者哪个先启动时,可以两边重复声明消息队列。
    channel.queue_declare(queue='python-test', durable=False)
    # 定义一个回调函数来处理消息队列中的消息,这里是打印出来
    def callback(ch, method, properties, body):
        # 手动发送确认消息
        ch.basic_ack(delivery_tag=method.delivery_tag)
        print(body.decode())
        # 告诉生产者,消费者已收到消息
    
    # 告诉rabbitmq,用callback来接收消息
    # 默认情况下是要对消息进行确认的,以防止消息丢失。
    # 此处将auto_ack明确指明为True,不对消息进行确认。
    channel.basic_consume('python-test',
                          on_message_callback=callback)
                          # auto_ack=True)  # 自动发送确认消息
    # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
    channel.start_consuming()
    

消息分发模型

  • 生产者

    # 生产者代码
    import pika
    
    
    credentials = pika.PlainCredentials('guest', 'guest')  # mq用户名和密码
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',
                                                                   credentials=credentials))
    
    # 建立rabbit协议的通道
    channel = connection.channel()
    # 声明消息队列,消息将在这个队列传递,如不存在,则创建。durable指定队列是否持久化。确保没有确认的消息不会丢失
    channel.queue_declare(queue='rabbitmqtest', durable=True)
    
    # message不能直接发送给queue,需经exchange到达queue,此处使用以空字符串标识的默认的exchange
    # 向队列插入数值 routing_key是队列名
    # basic_publish的properties参数指定message的属性。此处delivery_mode=2指明message为持久的
    for i in range(10):
        print(i, "----")
        channel.basic_publish(exchange='',
                              routing_key='rabbitmqtest',
                              body='Hello world!%s' % i,
                              properties=pika.BasicProperties(delivery_mode=2))
    # 关闭与rabbitmq server的连接
    connection.close()
    
  • 消费者

    # 消费者代码,consume1与consume2
    import pika
    import time
    
    credentials = pika.PlainCredentials('guest', 'guest')
    # BlockingConnection:同步模式
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',
                                                                   credentials=credentials))
    channel = connection.channel()
    # 申明消息队列。当不确定生产者和消费者哪个先启动时,可以两边重复声明消息队列。
    channel.queue_declare(queue='rabbitmqtest', durable=True)
    # 定义一个回调函数来处理消息队列中的消息,这里是打印出来
    def callback(ch, method, properties, body):
        # 手动发送确认消息
        time.sleep(3)
        print(body.decode())
        # 告诉生产者,消费者已收到消息
        ch.basic_ack(delivery_tag=method.delivery_tag)
    
    # 如果该消费者的channel上未确认的消息数达到了prefetch_count数,则不向该消费者发送消息
    channel.basic_qos(prefetch_count=1)
    # 告诉rabbitmq,用callback来接收消息
    # 默认情况下是要对消息进行确认的,以防止消息丢失。
    # 此处将no_ack明确指明为True,不对消息进行确认。
    channel.basic_consume('rabbitmqtest',
                          on_message_callback=callback,)
                          # auto_ack=True)  # 自动发送确认消息
    # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
    channel.start_consuming()
    
posted @ 2022-06-19 14:58  TY520  阅读(30)  评论(0编辑  收藏  举报