RabbitMQ 简单实例

Sender_Producer

import pika


# 创建Rabbitmq实例连接
credentials = pika.PlainCredentials('admin', '123456')
conn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost', credentials=credentials))

# 声明一个管道
channel = conn.channel()

# 管道里声明Queue
channel.queue_declare(queue='hello',    # 队列名称
                      durable=True)     # 消息持久化,需要配合properties

# RabbitMQ a message can never be sent directly to the queue, is always needs to go through an exchange.
channel.basic_publish(exchange='',
                      routing_key='hello',  # queue名字
                      body='Hello World Consumer!',     # 消息内容, 只能传递Str或者Unicode
                      properties=pika.BasicProperties(delivery_mode=2)   # 使消息持久化
                      )

print('[x] Sent "Hello World Consumer!"')
conn.close()

Receiver_Consumer

import pika

# 创建RabbitMQ连接
credentials = pika.PlainCredentials('admin', '123456')
conn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost', credentials=credentials))

# 管道声明
channel = conn.channel()

# 为什么又在Receiver中声明了一个'hello'队列?
# 如果确定已经声明了,就可以不用声明。但是你不知道Sender还是Receiver谁先运行,所以建议在Sender和Receiver中声明!
channel.queue_declare(queue='hello',    # 队列名称
                      durable=True)     # 消息持久化


# 定义回调函数
def callback(ch, method, properties, body):
    print(ch, method, properties)
    print('[x] Received %r' % body)
    ch.basic_ack(delivery_tag=method.delivery_tag)   # 告诉Producer消息处理完成

channel.basic_qos(prefetch_count=1)  # 类似权重,按能力分发,如果有一个消息,就不在给你发
channel.basic_consume(callback,  # 如果接收到消息,就调用callback函数
                      queue='hello',  # 从哪个队列中接收消息
                      no_ack=False)  # False表示需要做消息确认,防止宕机消息丢失

print('[*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

 

posted @ 2018-01-14 20:16  Vincen_shen  阅读(137)  评论(0)    收藏  举报