#send.py
import pika
import sys
# 创建连接
connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
# 创建channel
channel = connection.channel()
message = " ".join(sys.argv[1:]) or "hello world"
# 创建队列,并持久化存储
channel.queue_declare(queue="hello", durable=True)
channel.basic_publish(exchange='', routing_key="hello", body="message",
properties=pika.BasicProperties(delivery_mode=2))
connection.close()
#receive.py
import pika
import time
# 创建连接
connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
# 创建channel
channel = connection.channel()
# 创建队列
channel.queue_declare(queue="hello", durable=True)
# 回调函数
def callback(ch, method, properties, body):
print("[x] Received %r" % (body,))
print(type(body))
time.sleep(5)
print("[x] Done")
ch.basic_ack(delivery_tag=method.delivery_tag)
# 公平调度,让每个消费者执行时间相近
channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback, queue="hello")
# 阻塞,等待接收
channel.start_consuming()