06RabbitMQ_生产者消费者模式
import pika # 声明socket链接 connection = pika.BlockingConnection(pika.ConnectionParameters("localhost")) # 创建链接的管道 channel = connection.channel() # 声明要传输的数据队列,并创建队列的名称为hello,durable=True表示持久化保存队列名称.. channel.queue_declare(queue='hello',durable=True) channel.basic_publish( exchange='', routing_key='hello', body='这是发送的消息主体', properties=pika.BasicProperties( delivery_mode=2#保持队列中的内容持久化保存 ) ) print("消息已经发送") # 关闭socket链接 connection.close()
import pika # 因为不知道是生产者先开启,还是消费者先开启管道,所有两边均要声明管道 connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() # 定义队列 channel.queue_declare(queue='hello',durable=True) # 定义一个函数,处理接受数据后进行处理 def callback(ch, method, properties, body): print(ch)# ch为声明的管道的内存地址 print(method) print(properties) print("接受的消息:%s" % body.decode()) # 定义一个处理消息的返回,当消费者接收到消息会发送给生产者一个消息.生产者接收消息后,确认消费者已经接收消息, # 在队列中就会将消息删除.不会发送给下一个消费者 ch.basic_ack(delivery_tag=method.delivery_tag) # 当消费者消息队列中还有一条消息的时候,不给当前消费者发送消息 channel.basic_qos(prefetch_count=1) # 声明1.接受消息后要怎么处理,2.要接受的队列名称 channel.basic_consume( callback, queue='hello', #no_ack=True ) # 开始接受生产者发送的消息,当没有消息的时候程序会等在下面,等着 channel.start_consuming()