import pika
import time
from pika.exceptions import StreamLostError
while True:
try:
def rabbitmq_receive():
# 连接到RabbitMQ服务器
credentials = pika.PlainCredentials('admin', 'admin123')
connection = pika.BlockingConnection(pika.ConnectionParameters('172.30.12.32', 5672, '/', credentials))
# 建立一个交换器
channel = connection.channel()
# 绑定交换器和队列
channel.queue_bind(queue='MY_DIRECT_GOODS_QUEUE', exchange='my_direct_exchange', routing_key='')
# 定义一个回调函数来处理接收到的消息
def on_message_callback(ch, method, properties, body):
print("Received message: %r %r" % (body, properties))
ch.basic_ack(delivery_tag=method.delivery_tag)
# 指定回调函数
channel.basic_consume(queue='MY_DIRECT_GOODS_QUEUE', on_message_callback=on_message_callback,
auto_ack=False)
# channel.exchange_declare(exchange='my_direct_exchange', exchange_type='direct', durable=True)
# 开始接收消息,进入无限循环,直到手动中断程序
print("等待接收消息...")
channel.start_consuming()
connection.close()
rabbitmq_receive()
except pika.exceptions.StreamLostError as e:
print(e.args)
time.sleep(3)
continue