#测试目的:RabbitMQ消息分发轮询
#1. 启动两个receive端口,并在callbackup睡眠30秒。
#2. send端口发送数据。
#3. 当第一个receive端收到信息后,立刻第一个程序中止。
#4. 查看第二个receive端是否再收到(正常能收到)

#RabbitMQ 的队列信息,只会在客户端确认收到后才会取消,否则一直存在,
#并且体现了RabbitMQ的分发轮询机制,第一个收了,然后到第二个,或者第一个收不了,第二个收。
#send 端

import pika

credentials = pika.PlainCredentials('root', 'Password1')

connection = pika.BlockingConnection(pika.ConnectionParameters('10.3.151.86',5672,'/',credentials))

channel = connection.channel()          #通过connection实例创建一个channel管道

channel.queue_declare(queue='hello')    #在管道中创建一个队列

channel.basic_publish(exchange='',routing_key='hello',body='Hello Wfffforld!')

connection.close()


#receive 端
import pika
import time

credentials = pika.PlainCredentials('root', 'Password1')

connection = pika.BlockingConnection(pika.ConnectionParameters('10.3.151.86',5672,'/',credentials))

channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch,method,properties,body):     #回调函数
    time.sleep(30)                        #增加30秒等待
    print(" [x] Received %r" % body)
    ch.basic_ack(delivery_tag=method.delivery_tag)     #通知服务端已确认收到

channel.basic_consume(
    callback,
    queue='hello',
    # no_ack=True         #默认不写是指返回给服务器是否获取数据成功
)

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

channel.start_consuming()