1,简介html
pip install pika
3.示例测试python
实例的内容就是从send.py发送消息到rabbitmq,receive.py从rabbitmq接收send.py发送的信息。windows
P表示produce,生产者的意思,也能够称为发送者,实例中表现为send.py;服务器
C表示consumer,消费者的意思,也能够称为接收者,实例中表现为receive.py;dom
中间红色的表示队列的意思,实例中表现为hello队列。测试
send.pyspa
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 4 import pika 5 import random 6 7 # 新建链接,rabbitmq安装在本地则hostname为'localhost' 8 hostname = '192.168.1.133' 9 parameters = pika.ConnectionParameters(hostname) 10 connection = pika.BlockingConnection(parameters) 11 12 # 建立通道 13 channel = connection.channel() 14 # 声明一个队列,生产者和消费者都要声明一个相同的队列,用来防止万一某一方挂了,另外一方能正常运行 15 channel.queue_declare(queue='hello') 16 17 number = random.randint(1, 1000) 18 body = 'hello world:%s' % number 19 # 交换机; 队列名,写明将消息发往哪一个队列; 消息内容 20 # routing_key在使用匿名交换机的时候才须要指定,表示发送到哪一个队列 21 channel.basic_publish(exchange='', routing_key='hello', body=body) 22 print " [x] Sent %s" % body 23 connection.close()
receive.py命令行
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 4 import pika 5 6 hostname = '192.168.1.133' 7 parameters = pika.ConnectionParameters(hostname) 8 connection = pika.BlockingConnection(parameters) 9 10 # 建立通道 11 channel = connection.channel() 12 channel.queue_declare(queue='hello') 13 14 15 def callback(ch, method, properties, body): 16 print " [x] Received %r" % (body,) 17 18 # 告诉rabbitmq使用callback来接收信息 19 channel.basic_consume(callback, queue='hello', no_ack=True) 20 21 # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理,按ctrl+c退出 22 print ' [*] Waiting for messages. To exit press CTRL+C' 23 channel.start_consuming()
咱们先运行send.py发送消息:code
再运行receive.py接收消息:htm