UP | HOME

基础概念

Table of Contents

RabbitMQ

接收,存储,转发消息

message

数据

producer

发送消息者

producer.png

Figure 1: producer

queue

类似于邮箱

queue.png

Figure 2: queue

consumer

等待接受消息者

consumer.png

Figure 3: consumer

AMQP

通用的消息协议

Hello World

hello_world.png

Figure 4: send/receive message

发送消息

sending.png

Figure 5: send/receive message

  • 和RabbitMQ服务器建立连接
    #!/usr/bin/env python
    import pika
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        'localhost'))
    channel = connection.channel()
    
  • 声明要发送消息的队列
    channel.queue_declare(queue='hello')
    
  • 发送消息给exchange
    channel.basic_publish(exchange='',
                          routing_key='hello',
                          body='Hello World!')
    print(" [x] Sent 'Hello World!'")
    
  • 关闭连接
    connection.close()
    

接收消息

receiving.png

Figure 6: send/receive message

  • 创建连接,声明队列
    #!/usr/bin/env python
    import pika
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
    channel = connection.channel()
    
    channel.queue_declare(queue='hello')
    
  • 编写接受消息的回调函数
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)
    
  • 给队列注册回调函数
    channel.basic_consume(callback,
                          queue='hello',
                          no_ack=True)
    
  • 开始准备接受消息
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()
    

测试

  • 创建队列,准备接受消息
    $ python receive.py
    [*] Waiting for messages. To exit press CTRL+C
    [x] Received 'Hello World!'
    
  • 发送消息
    $ python send.py
    [x] Sent 'Hello World!'
    

Next:工作队列

Home:目录