send一条信息
# 连接rabbitmq的库
import pika
#建立连接
connection=pika.BlockingConnection(pika.ConnectionParameters('localhost'))
#在连接中得到管道
channel=connection.channel()
#创建一个hello队列
channel.queue_declare(queue='hello')
#在队列里创建消息,默认使用 '' exchange交换机
#队列名就叫hello
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
#关闭连接,节省资源
connection.close()
receive一条信息
import pika
#接受消息
connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel=connection.channel()
#输出消息的方法
def callback(ch, method, properties, body):
print(" 这是消息内容 %r" %body)
#声明队列
channel.queue_declare(queue='hello')
#这循环queue ,
channel.basic_consume(
queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()