python-python基础11

一、RabbitMQ队列

安装rabbitMQ:

https://www.cnblogs.com/jehuzzh/p/12560038.html

安装python rabbitMQ module 

pip install pika(python通过pika这个模块与rabbitMQ建立通信)

实现最简单的队列通信

 producer:

import pika

connection=pika.BlockingConnection(pika.ConnectionParameters('localhost'))  #建立一个socket
channel=connection.channel()
#声明一个queue
channel.queue_declare(queue='hello')
#生成消息,消息不能直接发到队列,需要通过exchange
channel.basic_publish(exchange='',
                     routing_key='hello',   #queue名
                     body='Hello World!')   #消息内容

print("send Hello World!")

connection.close()

consumer:

import pika

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

#您可能会问为什么我们再次声明队列‒我们已经在producer中声明了它。
#如果我们确定队列已经存在,我们就可以不再声明。
#但是我们不确定先运行哪个程序,所以在consumer中再声明一次queue就可以避免报错
channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)  #body就是消息内容

channel.basic_consume('hello',callback,auto_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()  #启动consumer,会一直等待接收消息

猜你喜欢

转载自www.cnblogs.com/jehuzzh/p/12563519.html