驱动库版本pika == 1.0.0,截止2019.04.01是最新版本。
首先说一下现在网上python3操作RabbitMQ教程在该版本的pika下不能用,这也是写这篇文章的目的所在。
生产者
import pika
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, '/', credentials))
channel = connection.channel()
channel.queue_declare(queue='my_key') # 连接指定队列,没有的话会自动创建
channel.basic_publish(exchange='', routing_key='my_key', body='Hello world!')
print("添加完毕")
connection.close()
消费者
import pika
user_pwd = pika.PlainCredentials('guest', 'guest')
s_conn = pika.BlockingConnection(pika.ConnectionParameters('localhost', credentials=user_pwd))
chan = s_conn.channel()
chan.queue_declare(queue='my_key')
def callback(ch, method, properties, body): # 回调函数
print("comsumer recv %s" % body)
chan.basic_consume(queue='my_key', on_message_callback=callback, auto_ack=True)
print('comsumer waiting ...')
chan.start_consuming()