RabbitMQ --> 消息队列
threading Queue --> 线程之间进行交互,不能跨进程进行
process Queue --> 父进程与子进程进行交互,或者同属于一个父进程下多个子进程进行交互。
当要进行不同程序或不同机器之间的交互就要用到RabbitMQ
代码范例1:简单的一收一发
# send端
#!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() # 声明管道 channel.queue_declare(queue='hello') #声明queue # RabbitMQ的消息永远不会被直接发送到队列中,它总是需要经过一次交换。 channel.basic_publish(exchange='', routing_key='hello', # queue名字 body='Hello World!') # 消息体 print(" [x] Sent 'Hello World!'") connection.close()
# receive端
#_*_coding:utf-8_*_ import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() # 声明管道 # server端已经声明了队列。 如果可以确信队列已经存在,则可以不写。 # 例如,send.py程序先运行。 但我们不能确定首先运行哪个程序。 # 因此,重复声明两个程序中的队列是一个好习惯。 channel.queue_declare(queue='hello') def callback(ch, method, properties, body): # ch:管道channel内存对象地址 print(" [x] Received %r" % body) channel.basic_consume( # 消费消息 callback, # 如果收到消息,就调用callback函数来处理消息 queue='hello', # queue名字 no_ack=True) # 不返回消息是否处理完成信号 # consume消费完消息会返回给produce一个信号(callback),produce收到信号以后才将该消息删除 print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()