rabbitmq-理论-Hello World!

理论:http://rabbitmq.mr-ping.com/tutorials_with_python/[1]Hello_World.html


将代码整合到一起

send.py的完整代码:

#!/usr/bin/env python
import pika

connection =
pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

(send.py源码)

receive.py的完整代码:

#!/usr/bin/env python
import pika

connection =
pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

(receive.py源码)

现在我们可以在终端中尝试一下我们的程序了。
首先我们启动一个消费者,它会持续的运行来等待投递到达。

python receive.py
# => [*] Waiting for messages. To exit press CTRL+C
# => [x] Received 'Hello World!'

然后启动生产者,生产者程序每次执行后都会停止运行。

python send.py
# => [x] Sent 'Hello World!'

成功了!我们已经通过RabbitMQ发送第一条消息。你也许已经注意到了,receive.py程序并没有退出。它一直在准备获取消息,你可以通过Ctrl-C来中止它。


猜你喜欢

转载自blog.csdn.net/zhuchunyan_aijia/article/details/80228893