分布式消息服务RABBITMQ版-Python客户端使用说明:消费消息

时间:2024-07-17 10:36:18

消费消息

以下加粗内容需要替换为实例自有信息,请根据实际情况替换。

  • SSL认证方式
    import pika
    import ssl
    
    # 连接信息
    conf = {
        'host': 'ip',
        'port': 5671,
        'queue_name': 'queue-test',
        'username': 'root',
        'password': 'password'
    }
    
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    credentials = pika.PlainCredentials(conf['username'], conf['password'])
    parameters = pika.ConnectionParameters(conf['host'],
                                           conf['port'],
                                           '/',
                                           credentials,
                                           ssl_options=pika.SSLOptions(context))
    
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.queue_declare(conf['queue_name'])
    
    
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body.decode('utf-8'))
    
    
    channel.basic_consume(queue=conf['queue_name'], on_message_callback=callback, auto_ack=True)
    
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()
  • 非SSL认证方式
    import pika
    
    # 连接信息
    conf = {
        'host': 'ip',
        'port': 5672,
        'queue_name': 'queue-test',
        'username': 'root',
        'password': 'password'
    }
    
    credentials = pika.PlainCredentials(conf['username'], conf['password'])
    parameters = pika.ConnectionParameters(conf['host'],
                                           conf['port'],
                                           '/',
                                           credentials)
    
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.queue_declare(conf['queue_name'])
    
    
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body.decode('utf-8'))
    
    
    channel.basic_consume(queue=conf['queue_name'], on_message_callback=callback, auto_ack=True)
    
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()
support.huaweicloud.com/devg-rabbitmq/rabbitmq-devg-003.html