生产者:
- # !/usr/bin/env python
- # -*- coding: utf-8 -*-
- 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 12334!')
- print("[x] Sent'生产者发送消息'")
- connection.close()
消费者:
- # !/usr/bin/env python
- # -*- coding: utf-8 -*-
- 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 %s" % body)
- ch.basic_ack(delivery_tag=method.delivery_tag) # 应答信号
- channel.basic_consume(queue='hello',
- on_message_callback=callback,
- # auto_ack=True) # 无应答模式
- auto_ack=False) # 应答模式
- print('[x] Waiting for messages. To exit press CTRL+C')
- channel.start_consuming()
来源: http://www.bubuko.com/infodetail-3320166.html